Answers for "unity 2d rotate towards direction"

C#
2

how to make a object rotate towards a position in 2d unity

Vector3 targ = staticCompassTarget.transform.position;
 targ.z = 0f; 
 Vector3 objectPos = transform.position;  
 targ.x = targ.x - objectPos.x;  
 targ.y = targ.y - objectPos.y;      
 float angle = Mathf.Atan2(targ.y, targ.x) * Mathf.Rad2Deg;   
 transform.rotation = Quaternion.Euler(new Vector3(0, 0, angle));
Posted by: Guest on December-31-2020
5

unity rotate vector

Vector3 rotated = Quaternion.AngleAxis(-45, Vector3.up) * vector;
Posted by: Guest on May-23-2020
2

unity 2d rotate towards direction

/// <summary>
    /// Rotate a gameobject to face a direction in 2D space with offet
    /// </summary>
    /// <param name="target"></param>
    /// <param name="RotationSpeed"></param>
    /// <param name="offset"></param>
    private void RotateGameObject(Vector3 target, float RotationSpeed, float offset)
    {
        //https://www.youtube.com/watch?v=mKLp-2iseDc
        //get the direction of the other object from current object
        Vector3 dir = target - transform.position;
        //get the angle from current direction facing to desired target
        float angle = Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg;
        //set the angle into a quaternion + sprite offset depending on initial sprite facing direction
        Quaternion rotation = Quaternion.Euler(new Vector3(0, 0, angle + offset));
        //Roatate current game object to face the target using a slerp function which adds some smoothing to the move
        transform.rotation = Quaternion.Slerp(transform.rotation, rotation, RotationSpeed * Time.deltaTime);
    }
Posted by: Guest on May-03-2020

Code answers related to "unity 2d rotate towards direction"

C# Answers by Framework

Browse Popular Code Answers by Language