一、需求描述:
初始情況——

目標需求:

二、代碼
1 void Update () { 2 // 獲取鼠標位置相對移動向量 3 Vector2 translation = new Vector2(Input.GetAxis("Horizontal"),Input.GetAxis("Vertical")); 4 // 根據鼠標位置相對移動向量移動物體 5 transform.Translate(translation * speed * Time.deltaTime); 6 // 當鼠標左鍵按下時 7 if (Input.GetMouseButton(0)) 8 { 9 // 鼠標坐標默認是屏幕坐標,首先要轉換到世界坐標 10 // 物體坐標默認就是世界坐標 11 // 兩者取差得到方向向量 12 Vector3 direction = Camera.main.ScreenToWorldPoint(Input.mousePosition) - transform.position; 13 // 方向向量轉換為角度值 14 float angle =360-Mathf.Atan2(direction.x, direction.y) * Mathf.Rad2Deg; 15 // 將當前物體的角度設置為對應角度 16 transform.eulerAngles = new Vector3(0, 0, angle); 17 } 18 19 }
