unity實(shí)現(xiàn)鼠標(biāo)拖住3D物體
本文實(shí)例為大家分享了unity實(shí)現(xiàn)鼠標(biāo)拖住3D物體的具體代碼,供大家參考,具體內(nèi)容如下
把該腳本直接掛在要拖拽的物體上即可
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ModelDrages : MonoBehaviour
{
//發(fā)射射線的攝像機(jī)
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);
//從攝像機(jī)發(fā)出到點(diǎn)擊坐標(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;
}
}
}
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
如何在C#中使用 CancellationToken 處理異步任務(wù)
這篇文章主要介紹了如何在C#中使用 CancellationToken 處理異步任務(wù),幫助大家更好的理解和學(xué)習(xí)使用c#,感興趣的朋友可以了解下2021-03-03
C#中實(shí)現(xiàn)抽象類里建立靜態(tài)方法
這篇文章主要介紹了C#中實(shí)現(xiàn)抽象類里建立靜態(tài)方法,需要的朋友可以參考下2014-07-07
C#使用SqlConnection連接到SQL Server的代碼示例
這篇文章主要介紹了C#使用SqlConnection連接到SQL Server的代碼示例,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-03-03
通過實(shí)例解析c# yield關(guān)鍵字使用方法
這篇文章主要介紹了通過實(shí)例解析c# yield關(guān)鍵字使用方法,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-09-09
unity中實(shí)現(xiàn)Edge瀏覽器鼠標(biāo)手勢(shì)的功能思路詳解
這篇文章主要介紹了unity中實(shí)現(xiàn)Edge瀏覽器鼠標(biāo)手勢(shì)的功能思路詳解,實(shí)現(xiàn)起來其實(shí)并不復(fù)雜,涉及的技術(shù)點(diǎn)有pc端和移動(dòng)端屏幕拖動(dòng)事件,二維向量的相關(guān)運(yùn)算,手勢(shì)匹配算法,事件系統(tǒng)設(shè)計(jì)模式,需要的朋友可以參考下2023-12-12
C#實(shí)現(xiàn)圖片放大功能的按照像素放大圖像方法
這篇文章主要介紹了C#實(shí)現(xiàn)圖片放大功能的按照像素放大圖像方法,功能非常實(shí)用,需要的朋友可以參考下2014-07-07

