If you are familiar with the game Soul knight they have an aiming system in which the gun rotates on the z-axis to face the closest enemy and I was wondering how that would work?
Not familiar with the game, but you can use Atan2 for this.
Vector3 direction = target.position - player.position;
float angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;
player.rotation = Quaternion.AngleAxis(angle, Vector3.forward);
Should work.
Exactly this. In fact, I attached a little cheesy demo package using that function to make a missile chase you in 2D.
From the attached package, this is the relevant snippet:
private void UpdateMissile()
{
// cartesian distance to player
Vector3 delta = Player.transform.position - Missile.transform.position;
// what heading is that?
float DesiredHeadingToPlayer = Mathf.Atan2(delta.y, delta.x) * Mathf.Rad2Deg;
// are we good enough?
float AngleError = Mathf.DeltaAngle(DesiredHeadingToPlayer, CurrentMissileHeading);
// nope, then turn!
if (Mathf.Abs( AngleError) > AcceptableAngleError)
{
CurrentMissileHeading = Mathf.MoveTowardsAngle(CurrentMissileHeading, DesiredHeadingToPlayer, MissileTurnRate * Time.deltaTime);
}
... etc.
does this work in 2d?
Look at the inputs to Atan2(): there’s only two of them, and it gives you an angle.
Not only does it work in 2D, but it ONLY works in 2D. It can be any dimensions you want but it’s only 2 of 'em.
The general 3D version of that is Vector3.Angle() but you don’t need that.