Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

trying to get 2D missiles to face my mouse. But having a very hard time, please help.

Discussion in '2D' started by NathanGroovy333, Apr 26, 2014.

  1. NathanGroovy333

    NathanGroovy333

    Joined:
    Nov 20, 2013
    Posts:
    8
    I've been trying to get my 2D object to point in the direction of the mouse. I've been looking everywhere online and
    and I've tried pasting many different pieces of code to get my object to look at the mouse. But none of them seem to
    work. This is what I've got at the moment for tracking the mouse:

    Vector3 mousePos = Input.mousePosition;
    mousePos.z = -(transform.position.x - Camera.main.transform.position.x);

    Vector3 worldPos = Camera.main.ScreenToWorldPoint(mousePos);

    transform.LookAt(worldPos);

    I put that code on my object, and it looks like it should work. But when I run it, its not pointed anywhere near the mouse.
    and goes in all sorts of directions. I could really use some help on how to figure this out. :(
     
  2. zombiegorilla

    zombiegorilla

    Moderator

    Joined:
    May 8, 2012
    Posts:
    8,952
    LookAt will rotate the whole object which you don't want as with a 2d object forward faces the camera. Instead, just rotate around the axis based on the mouse position. Like this:

    Code (csharp):
    1.  
    2.         Vector3 worldPos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
    3.         transform.rotation = Quaternion.AngleAxis((Mathf.Atan2(worldPos.y, worldPos.x) * Mathf.Rad2Deg)-90, Vector3.forward);
    4.  
    The -90 is to adjust for if your image point up, if it points right, remove it.
     
  3. NathanGroovy333

    NathanGroovy333

    Joined:
    Nov 20, 2013
    Posts:
    8
    It didn't really seem to work for me...Now the missile just points straight down. And it doesn't seems to rotate at all when I move the mouse.
     
    Last edited: Apr 27, 2014
  4. NathanGroovy333

    NathanGroovy333

    Joined:
    Nov 20, 2013
    Posts:
    8
    Never mind, I got it to work. I just had to set my camera to Orthographic in the inspector. Thanks for the help! :)
     
  5. zombiegorilla

    zombiegorilla

    Moderator

    Joined:
    May 8, 2012
    Posts:
    8,952
    Heh, yea a perspective camera will get odd results in 2d. ;)