使用鼠标位置旋转播放器的功能基于鼠标距离而不是位置

时间:2020-03-03 04:29:48

标签: c# unity3d

我在Unity论坛上回答了如何根据鼠标的位置旋转对象。该代码可用于更改旋转,但是可以使用其他参数旋转对象,如您在此记录中所见。

enter image description here

这是我用于鼠标检测和位置编辑的代码(来自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

如果您需要更多信息,请对其进行评论。

1 个答案:

答案 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);

}

所以这应该只在播放器上。

相关问题