Unity - Gameobject look at mouse

牧云@^-^@ 提交于 2019-12-31 01:19:32

问题


I've ran into a problem.

The basic setup I have right now, two objects: my camera, and my player object.

The player moves via Transform on WASD, and is supposed to rotate on mouse movement.

The camera is top down (At a slight "3ps" style angle, which keeps the player object centre to the camera's perspective, and rotates according to the players rotation.

This is the players movement script: http://pastebin.com/SvN8FuWs

This is the players rotation script: http://pastebin.com/uzZ7SKFL

The result of everything I have shown is it rotates, but it doesn't rotate true to where the mouse physically is.

While I draw circles with the mouse, it will do full rotations, but not consistently point to where the mouse is. I'm not sure as to why.

The desired result is for the camera (child of player object) to follow the players movement and rotation, while the player moves with its movement script, and rotates to point true to where the mouse is.

Anyone got any ideas? Thanks in advance.

Edit: if it helps, the current rotation works like this.

drawing large circles with the mouse around the player gives a slower rotation, than extremely tight circles around the player.


回答1:


I'm not sure If I understand what you are trying to do. If you are trying to do something similar to the game "Dead Nation", then I would suggest something like this:

MouseLook.cs

void Update()
{
    Vector3 mouse = Input.mousePosition;
    Vector3 mouseWorld = Camera.main.ScreenToWorldPoint(new Vector3(
                                                        mouse.x, 
                                                        mouse.y,
                                                        player.transform.position.y));
    Vector3 forward = mouseWorld - player.transform.position;
    player.transform.rotation = Quaternion.LookRotation(forward, Vector3.up);
}

If you want the camera to move and rotate along with the player then just make the camera a child of the player object.



来源:https://stackoverflow.com/questions/36615476/unity-gameobject-look-at-mouse

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!