unity 滑鼠拖動 物體旋轉 點選變色 拖動移動
阿新 • • 發佈:2019-02-05
public Camera camera; Ray ray; RaycastHit hitInfo; Vector3 offset; GameObject obj;//獲取點選到的物體 public GameObject transformObj; Vector3 startMousePosition; // Use this for initialization void Start () { startMousePosition = Input.mousePosition; } // Update is called once per frame void Update () { if (Input.GetMouseButtonDown (0)) { ray = camera.ScreenPointToRay (Input.mousePosition); if (Physics.Raycast (ray, out hitInfo)) { obj = GameObject.Find (hitInfo.transform.name); obj.GetComponent<MeshRenderer>().material.color = new Color(Random.Range (0f, 1f),Random.Range (0f, 1f),Random.Range (0f, 1f),Random.Range (0f, 1f)); } } if (Input.GetMouseButton (0)) { if (obj) { //將物體由世界座標轉為螢幕座標ScreenToWorldPoint Vector3 screenObj = Camera.main.WorldToScreenPoint(obj.transform.position); //儲存滑鼠的螢幕座標 z使用目標物體的螢幕座標 Vector3 screenMouse = new Vector3(Input.mousePosition.x, Input.mousePosition.y,screenObj.z); offset =Camera.main.ScreenToWorldPoint(screenMouse)- obj.transform.position ; Vector3 currentPosition = obj.transform.position + offset; obj.transform.position = currentPosition; } } if (Input.mousePosition != startMousePosition && !Input.GetMouseButton(0)&& !Input.GetMouseButtonDown(0)) { Vector3 screenObj = Camera.main.WorldToScreenPoint(transformObj.transform.position); Vector3 screenMouse = Input.mousePosition; Vector3 newVector = screenMouse - screenObj; transformObj.transform.forward = newVector; } }
座標轉換參考文件點選開啟連結transform.position = new Vector3 (Mathf.MoveTowards (transform.position.x, ball.transform.position.x, speed * Time.deltaTime), Mathf.MoveTowards (transform.position.y, ball.transform.position.y- 2f, speed * Time.deltaTime), Mathf.MoveTowards (transform.position.z, ball.transform.position.z , speed * Time.deltaTime));