使用鼠标位置旋转玩家的功能基于鼠标距离而不是位置 [英] Function to rotate player with mouse position is based on mouse distance instead of position

查看:37
本文介绍了使用鼠标位置旋转玩家的功能基于鼠标距离而不是位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遵循了 Unity 论坛上关于如何根据鼠标的位置旋转对象的答案.该代码可用于更改旋转,但它使用其他一些参数来旋转对象,如您在此录制中所见.

I followed an answer on the Unity Forums on how to rotate an object according to the position of the mouse. The code works for changing the rotation, but it uses some other parameter to rotate the object, as you can see in this recording.

这是我的鼠标检测和位置编辑代码(来自 Game.csupdate() 函数:

Here is my code for the mouse detection and position editing (from Game.cs's update() function:

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

这是申请位置的代码(来自PlayerScript.csupdate()函数.:

Here is the code for the position applying (from PlayerScript.cs's update() function.:

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

如果您需要更多信息,请评论.

If you need any more information, please comment it.

推荐答案

首先,您似乎暗示您在两个不同的对象上有此代码.您应该创建一个名为LookAtMouse"的脚本.不管你把它放在什么东西都会看着鼠标.

First things, you seem to imply that there you have this code on two different objects. You should create a single script called "LookAtMouse". Whatever you put this on if what will look at the mouse.

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

}

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

So this should be only on the player.

这篇关于使用鼠标位置旋转玩家的功能基于鼠标距离而不是位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆