【Unity3D】使用鼠標控制物體在世界坐標中移動

public class Move : MonoBehaviour {

? ? ?public GameObject cube;? //要拖拽的物體

? ? Vector3 mouseV3;? ? //鼠標

? ? Vector3 screeenV;? //存儲cube的屏幕坐標

? ? Vector3 world;? ? //記錄鼠標坐標轉成的世界坐標


void Update() {

if (Input.GetMouseButtonDown(0)) {

? ? ? ? ? ? ? //當鼠標第一次單擊時記錄下cube在場景中的坐標,并把世界坐標轉成屏幕坐標

? ? ? ? ? ? screeenV= Camera.main.WorldToScreenPoint(cube.transform.position);

}

if (Input.GetMouseButton(0)){

? ? ? ? ? ? ? ? ? ? mouseV3 = Input.mousePosition;? //當鼠標移動時記錄下鼠標的坐標

? ? ? ? ? ? ? ? ? ?mouseV3.z = screeenV.z;? //因為鼠標的z坐標為0,所以需要一個z坐標

? ? ? ? ? ? ? ? ? //把鼠標的屏幕坐標轉換成世界坐標

? ? ? ? ? ? ? ? ? world = Camera.main.ScreenToWorldPoint(mouseV3);

? ? ? ? ? ? ? ? ?//當鼠標移動時,cube也發(fā)生移動,為了讓cube的y軸不發(fā)生移動,設y軸為原來的y軸

? ? ? ? ? ? ? ? ? cube.transform.position = new Vector3(world.x, cube.transform.position.y, world.z);

? ? ? ? ? ? ? ? ?print(cube.transform.position);

? ? ? ? ?}

? ?}

}

最后編輯于
?著作權歸作者所有,轉載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容