雷火电竞-中国电竞赛事及体育赛事平台

歡迎來到入門教程網(wǎng)!

C#教程

當(dāng)前位置:主頁 > 軟件編程 > C#教程 >

unity實現(xiàn)鼠標(biāo)拖住3D物體

來源:本站原創(chuàng)|時間:2020-01-10|欄目:C#教程|點擊:

本文實例為大家分享了unity實現(xiàn)鼠標(biāo)拖住3D物體的具體代碼,供大家參考,具體內(nèi)容如下

把該腳本直接掛在要拖拽的物體上即可

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ModelDrages : MonoBehaviour 
{

//發(fā)射射線的攝像機
private Camera cam;
//射線碰撞的物體
private GameObject go;
//射線碰撞物體的名字
public static string btnName;
private Vector3 screenSpace;
private Vector3 offset;
private bool isDrage = false;

// Use this for initialization
void Start ()
{
  cam = Camera.main;
}

// Update is called once per frame
  void Update ()
{
  //整體初始位置
  Ray ray = cam.ScreenPointToRay(Input.mousePosition);
  //從攝像機發(fā)出到點擊坐標(biāo)的射線
  RaycastHit hitInfo;
  if (isDrage == false)
  {
    if(Physics .Raycast (ray,out hitInfo))
    {
      //劃出射線 只有在Scene視圖中才能看到
      Debug.DrawLine(ray.origin, hitInfo.point);
      go = hitInfo.collider.gameObject;
      print(btnName);
      screenSpace = cam.WorldToScreenPoint(go.transform.position);
      offset = go.transform.position - cam.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, Input.mousePosition.z));
      //物體的名字
      btnName = go.name;
      //組件的名字
    }
    else
    {
      btnName = null;
    }
  }
  if(Input.GetMouseButton(0))
  {
    Vector3 currentScreenSpace = new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenSpace.z);
    Vector3 currentPosition = cam.ScreenToWorldPoint(currentScreenSpace) + offset;
    if (btnName != null)
    {
      go.transform.position = currentPosition;
    }
    isDrage = true;
  }
  else
  {
    isDrage = false;
  }
 }

}

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持我們。

上一篇:微信公眾號被動消息回復(fù)原理解析

欄    目:C#教程

下一篇:C#語法之泛型的多種應(yīng)用

本文標(biāo)題:unity實現(xiàn)鼠標(biāo)拖住3D物體

本文地址:http://www.jygsgssxh.com/a1/C_jiaocheng/4716.html

網(wǎng)頁制作CMS教程網(wǎng)絡(luò)編程軟件編程腳本語言數(shù)據(jù)庫服務(wù)器

如果侵犯了您的權(quán)利,請與我們聯(lián)系,我們將在24小時內(nèi)進行處理、任何非本站因素導(dǎo)致的法律后果,本站均不負任何責(zé)任。

聯(lián)系QQ:835971066 | 郵箱:835971066#qq.com(#換成@)

Copyright © 2002-2020 腳本教程網(wǎng) 版權(quán)所有