Search Unity

how to make my gameobject facing the mouse cursor

Discussion in 'Scripting' started by fandiwhuang, Sep 5, 2011.

  1. fandiwhuang

    fandiwhuang

    Joined:
    Jul 24, 2011
    Posts:
    38
    Code (csharp):
    1.  
    2.  
    3.  
    4. private var target:GameObject;
    5.  
    6. function Start()
    7. {
    8.     target = GameObject.Find("gameCursor");
    9. }
    10.  
    11.  
    12. function Update ()
    13. {
    14.     transform.rotation.eulerAngles.x= 270;
    15.     transform.rotation.eulerAngles.z = 0;
    16.     transform.LookAt(target.transform);
    17.    
    18. }
    19.  
    20.  
    this is top down game and i need to make my character to face the "gameCursor" GameObject ( this gameobject is following wherever my mouse cursor goes) ..

    and i want this to rotate on y axis only and keep x = 270 and z = 0

    i used my script and somehow i i got my character turn upside down .

    help me plss :( i dont know what i've done wrong and im noob
     
  2. W4RH4WK117

    W4RH4WK117

    Joined:
    Feb 6, 2011
    Posts:
    129
  3. Biggz

    Biggz

    Joined:
    Aug 29, 2011
    Posts:
    23
    I have something similar set up in 2D, but my player object faces the direction of the X/Y input from an analogue joystick.
    Code (csharp):
    1.  
    2.         vDir.x = Input.GetAxis("Horizontal");
    3.         vDir.y = Input.GetAxis("Vertical");
    4.  
    5.         // Rotate player
    6.         float fAngle = Mathf.Atan2(vDir.x, vDir.y) * Mathf.Rad2Deg;
    7.         transform.rotation = Quaternion.AngleAxis(fAngle, Vector3.back);
    8.  
    It should work if you replace the Input.GetAxis to Input.mousePosition, and calculate the vector between your character and the mouse pointer. which would need translating to camera coordinates, rather than world coordinates.

    Or the link above could be the correct way to do it... my bit of code is what I came up with this weekend and I've only used Unity for 3days :)
     
    Last edited: Sep 5, 2011