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. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

Top down 2D Game, facing towards an object

Discussion in 'Editor & General Support' started by The_Widow_Maker, Sep 19, 2015.

  1. The_Widow_Maker

    The_Widow_Maker

    Joined:
    Nov 21, 2014
    Posts:
    10
    Hi all

    I am really struggling to get an object to rotate and face another object, I have read and tried many many of the solutions online but none seem to work for me. I will try to explain what I am trying to do as best as I can (picture included).

    (2D Project)
    I wanted to be able to move the cross to a square when it has been clicked on while facing the direction of the square, I have the cross moving to the correct squares but not facing the correct direction.

    In the picture I have attached I am trying to get the cross to rotate on the Z axis and face the squares on click, some of the solutions out there make the cross face the squares but rotate it in different places and make the cross looks strange, I am wanting the cross to look the same just change angle so that it is facing whichever square has been clicked on.

    using C#

    Any help would be appreciated

    Thanks
     

    Attached Files:

  2. CStunner

    CStunner

    Joined:
    Jul 12, 2013
    Posts:
    39
    2D LookAt

    Code (CSharp):
    1. float offset = 0f; // Change this if it doesn't work straight away
    2.  
    3. Vector3 targetPos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
    4. Vector3 myPos = transform.position;
    5.  
    6. Vector3 des = targetPos - myPos;
    7. float rotZ = Mathf.Atan2 (des.y, des.x) * Mathf.Rad2Deg;
    8. transform.rotation = Quaternion.Euler (0f, 0f, rotZ - offset);