我在Unity论坛上回答了如何根据鼠标的位置旋转对象。该代码可用于更改旋转,但是可以使用其他参数旋转对象,如您在此记录中所见。
这是我用于鼠标检测和位置编辑的代码(来自Game.cs
的{{1}}函数:
update()
以下是应聘职位的代码(来自playerLocation = PlayerScript.position;
playerRotation = PlayerScript.rotation;
mousePosition = Input.mousePosition;
mousePosition.z = 5.23f;
Vector3 objectPosition = Camera.main.WorldToScreenPoint (playerLocation);
mousePosition.x = mousePosition.x - playerLocation.x;
mousePosition.y = mousePosition.y - playerLocation.y;
float angle = Mathf.Atan2(mousePosition.y, mousePosition.x) * Mathf.Rad2Deg;
playerRotation = new Vector3(0f, 0f, angle);
的{{1}}函数。:
PlayerScript.cs
如果您需要更多信息,请对其进行评论。
答案 0 :(得分:1)
首先,您似乎暗示您在两个不同的对象上都有此代码。您应该创建一个名为“ LookAtMouse”的脚本。无论您将其戴在身上什么,只要能看到鼠标。
public Camera cam;
void Update() {
Vector3 direction = Input.mousePosition - cam.WorldToScreenPoint(transform.position);
float angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.AngleAxis(angle, Vector3.forward);
}
所以这应该只在播放器上。