在场景中除默认camera和light外,添加cube物体,并挂载脚本。
1 using System.Collections; 2 using System.Collections.Generic; 3 using UnityEngine; 4 5 public class ColliderDemo : MonoBehaviour { 6 7 private void OnMouseDrag() 8 { 9 Vector3 v = Input.mousePosition; 10 float f = Input.GetAxis(AxisName.MouseScrollWheel); 11 transform.position += transform.forward * f * 10f; 12 v.z = Mathf.Abs(Camera.main.transform.position.z - transform.position.z); 13 Debug.Log(Input.GetAxis(AxisName.MouseScrollWheel)); 14 gameObject.transform.localPosition = Camera.main.ScreenToWorldPoint(v); 15 } 16 }
值得注意的是ScreenToWorldPoint方法并未给z轴进行赋值所以需要自己给z轴赋值。v.z并不是cube的z轴而是摄像机和cube的距离。
效果图: