首页 > 代码库 > 鼠标控制物体移动
鼠标控制物体移动
1.物体移动到鼠标点击处
2.物体跟随鼠标移动
分为三步:获取鼠标位置、转化为世界坐标、物体移动
private Vector3 mopos;
private Vector3 gamepos;
void Start(){
//物体的世界坐标转化成屏幕坐标
//gamepos = Camera.main.WorldToScreenPoint (transform.position);
gamepos = transform.position;
}
void Update () {
//物体移动到鼠标点击处
if (Input.GetMouseButtonDown (0)) {
mopos = Input.mousePosition;//获取鼠标位置
//转化物体世界z坐标为屏幕坐标并赋值给鼠标z坐标
mopos.z=Camera.main.WorldToScreenPoint( transform.position).z;
//将需要的鼠标坐标转化成世界坐标
gamepos.x=Camera.main.ScreenToWorldPoint(mopos).x;
gamepos.z=Camera.main.ScreenToWorldPoint(mopos).z;
gamepos.y=transform.position.y;
}
//让物体移动到坐标处
transform.position = Vector3.Lerp (gameObject.transform.position,gamepos,Time.deltaTime*5f);
//朝向某处
//transform.LookAt (gamepos);
}
Ps:一个小例子,准星在屏幕中跟随鼠标移动
void Updata(){
mopos = Input.mousePosition;//获取鼠标位置
//调整位置比例
mopos.x /= 823.0f;
mopos.y /= 600.0f;
//移动
transform.position = Vector3.Lerp (gameObject.transform.position,mopos,Time.deltaTime*30f);
}
//物体朝向鼠标方向旋转
//获取鼠标增量
float h = Input.GetAxis("Mouse X");
float v = Input.GetAxis("Mouse Y");
//旋转
transform.Rotate(v, h, 0);
鼠标控制物体移动