Search code examples
unity-game-engineunityscript

Unity -- Camera Child of Player Rotates Uncontrollably


I have a camera that I want to stay at all times at the same position as the player. I did this by making it a child of the player, since when I did it through a script the player got ahead of the camera. I also have the camera rotating with the mouse. However, when I made the camera a child of the player, my player and camera now don't stop rotating, but continue when the mouse is motionless. I want the camera to rotate only when the mouse is moving. My code (JS):

    #pragma strict
var player : GameObject;
function Start () {
    player = GameObject.Find("Player");
    Cursor.visible = false;
}

function Update () {
    //transform.position = player.transform.position;
    transform.Rotate(Input.GetAxis("Mouse Y") * -2, Input.GetAxis("Mouse X") * 5, 0);
    transform.rotation.eulerAngles = new Vector3(transform.rotation.eulerAngles.x, transform.rotation.eulerAngles.y, 0);
    //player.transform.rotation = transform.rotation;
}

First commented out line is the now-unnecessary code that moves the camera to the player, the second line is the one that is causing problems. If I remove it, the camera rotates fine but the player can't turn (transform.forward-based controls). If I uncomment it, the player and camera turn with no friction and can't be controlled.


Solution

  • This isn't really how you make a mouse look controller. You should take a look at these controllers:

    https://forum.unity.com/threads/a-free-simple-smooth-mouselook.73117/

    http://wiki.unity3d.com/index.php/SmoothMouseLook

    Or this JS one: http://answers.unity3d.com/answers/367253/view.html