Search Unity

Mouse rotate script + character move script = weird movement.

Discussion in 'Scripting' started by IAmCraigSnedeker, Aug 20, 2014.

  1. IAmCraigSnedeker

    IAmCraigSnedeker

    Joined:
    Jul 20, 2014
    Posts:
    117
    Okay, so I have this simple script that makes my character (currently, a cube) look at my mouse.

    Code (CSharp):
    1. var mousePosition = Camera.main.ScreenToWorldPoint (Input.mousePosition);
    2. Quaternion rot = Quaternion.LookRotation (transform.position - mousePosition, Vector3.forward);
    3.  
    4. transform.rotation = rot;
    5. transform.eulerAngles = new Vector3 (0, transform.eulerAngles.y, 0);
    Works (yay!). But then I have the character move script (CharacterMove.cs) that also does what I want it do.

    Code (CSharp):
    1. void Update () {
    2.         if (Input.GetKey ("w"))
    3.             transform.Translate (Vector3.forward * moveSpeed * Time.deltaTime);
    4.         if (Input.GetKey ("s"))
    5.             transform.Translate (Vector3.back * moveSpeed * Time.deltaTime);
    6.         if (Input.GetKey ("a"))
    7.             transform.Translate (Vector3.left * moveSpeed * Time.deltaTime) ;
    8.         if (Input.GetKey ("d"))
    9.             transform.Translate (Vector3.right * moveSpeed * Time.deltaTime);
    10.     }
    But when combined, the character tries to follow the mouse when I move it.

    I dont want it to follow my mouse, only look at it, and movement is strictly controlled by the keyboard.

    How can I go about this?

    /complete noob
     
  2. Fraconte

    Fraconte

    Joined:
    Dec 6, 2013
    Posts:
    327
    You are moving relative to object orientation. If you want your movement to follow the world axis you have to modify all Translate like this:
    Code (CSharp):
    1.  
    2. transform.Translate (Vector3.forward * moveSpeed * Time.deltaTime, Space.World);
    3.  
     
    IAmCraigSnedeker likes this.
  3. IAmCraigSnedeker

    IAmCraigSnedeker

    Joined:
    Jul 20, 2014
    Posts:
    117
    Dude, that works perfect. Thank you!
     
  4. IAmCraigSnedeker

    IAmCraigSnedeker

    Joined:
    Jul 20, 2014
    Posts:
    117
    Another quick question, not completely related to the original post, but using the same scripts.

    The script works fine until I added a empty game object "hands" under the player (which has a cube), then it throws the rotation slightly off (the mouse is now at the right side of the cube instead in front of it, but if I disable "hands" it's fixed).



    It still rotates, but not exactly on the mouse. I think this is because it's now seeing the center of the player as a different location because the "gun" cube throws off the center-position of the player.

    How can I go about fixing this?