对象没有';t用鼠标指针移动
本文关键字:鼠标指针 移动 对象 | 更新日期: 2023-09-27 18:24:05
我有一个2d对象,当我单击鼠标按钮时,它会掉落,并且对象沿着x轴移动得很好。但它不会根据我的鼠标指针的x坐标移动,当我点击鼠标按钮时,它不会将对象放在鼠标指针所在的位置。我想解决对象沿x轴移动的问题。
代码:
public class Mouse : MonoBehaviour {
Rigidbody2D body;
float mousePosInBlocks;
void Start () {
body = GetComponent<Rigidbody2D> ();
}
void Update () {
if (Input.GetMouseButtonDown (0)) {
body.isKinematic = false;
}
Vector3 ballPos = new Vector3 (0f, this.transform.position.y, 0f);
mousePosInBlocks = Input.mousePosition.x / Screen.width * 4;
//restrict the position not outside
ballPos.x = Mathf.Clamp (mousePosInBlocks, -2.65f, 2.65f);
this.transform.position = ballPos;
}
}
要使对象与光标对齐,请使用camera.ScreenToWorldPoint
函数,而不是将鼠标位置除以Screen.width。简单地除以屏幕宽度是不正确的,因为如果游戏窗口不在屏幕角落,屏幕位置也可能有偏移。此处提供更多信息:http://docs.unity3d.com/ScriptReference/Camera.ScreenToWorldPoint.html
此外,只是一个建议——当使用刚体时,不要使用transform.position
,而是使用rigidbody.position
,这样效率会高得多。所以代码看起来是这样的:
using UnityEngine;
using System.Collections;
[RequireComponent(typeof(Rigidbody2D))]
public class Mouse : MonoBehaviour {
Rigidbody2D body;
float mousePosInBlocks;
void Start () {
body = GetComponent<Rigidbody2D> ();
}
void Update () {
if (Input.GetMouseButtonDown (0)) {
body.isKinematic = false;
}
Vector3 ballPos = new Vector3 (0f, this.transform.position.y, 0f);
mousePosInBlocks = Camera.main.ScreenToWorldPoint(Input.mousePosition).x;
//restrict the position not outside
ballPos.x = Mathf.Clamp (mousePosInBlocks, -2.65f, 2.65f);
body.position = ballPos;
}
}