Rotate 2D Object To Face Another Object Unity 2D Tutorial
#gamer #indiegame #gamedev
Support the channel and grab some great gaming merch at Green Man Gaming: https://greenmangaming.sjv.io/5gvEXn
https://linktr.ee/justaguyproduction
This is a VERY quick tutorial on rotating a 2d object to face another object. I noticed all the tutorials for this are 10+ minutes long, so I shortened the process to less than 3 minutes.
Here is the code that was used in the video:
public GameObject player;
public float speed;
public float rotationModifier;
private void FixedUpdate()
{
if (player != null)
{
Vector3 vectorToTarget = player.transform.position - transform.position;
float angle = Mathf.Atan2(vectorToTarget.y, vectorToTarget.x) * Mathf.Rad2Deg - rotationModifier;
Quaternion q = Quaternion.AngleAxis(angle, Vector3.forward);
transform.rotation = Quaternion.Slerp(transform.rotation, q, Time.deltaTime * speed);
}
}
This code was slightly modified from a Unity post. This is the original post: https://answers.unity.com/questions/650460/rotating-a-2d-sprite-to-face-a-target-on-a-single.html