Function to rotate/change animation of 2D sprites based on camera angle
Sat Mar 12 2022 12:43:16 GMT+0000 (Coordinated Universal Time)
Saved by @BryanJ22
void PlayerCameraAngle(Unit unit)
{
//This function rotates and changes the animation of characters using 2D Sprites.
//This allows us to use 2D Sprites in a 3D environment and gives the illusion that the sprites are 3D objects.
float MyPosX = Camera.main.transform.position.x;
float MyPosZ = Camera.main.transform.position.z;
float TargetPosX = unit.transform.position.x;
float TargetPosZ = unit.transform.position.z;
float angle = (float)((System.Math.Atan2(MyPosX - TargetPosX, MyPosZ - TargetPosZ) / System.Math.PI * 180.0f));
float offset = 22.5f;
Animator animator = unit.GetComponent<Animator>();
SpriteRenderer spriteRenderer = unit.GetComponent<SpriteRenderer>();
//Change angle depending on the direction the unit is moving in
if (unit.direction.x == 1)
{
angle += 90;
}
else if (unit.direction.x == -1)
{
angle -= 90;
}
else if (unit.direction.z == 1)
{
angle += 180;
}
//
//Do this to avoid negative values/values over 360
if (angle < 0)
{
angle += 360;
}
else if (angle > 360)
{
angle -= 360;
}
//
//We check 8 angle ranges for 8 directions and change the sprite animation based on the angle range
if (angle < (0 + offset) && angle > (0 - offset))
{
spriteRenderer.flipX = false;
currentAnimation = "Up";
animator.Play("Up");
}
if (angle < (45 + offset) && angle > (45 - offset))
{
spriteRenderer.flipX = false;
currentAnimation = "UpLeft";
animator.Play("UpLeft");
}
if (angle < (90 + offset) && angle > (90 - offset))
{
spriteRenderer.flipX = false;
currentAnimation = "Left";
animator.Play("Left");
}
if (angle < (135 + offset) && angle > (135 - offset))
{
spriteRenderer.flipX = false;
currentAnimation = "DownLeft";
animator.Play("DownLeft");
}
if (angle < (180 + offset) && angle > (180 - offset))
{
spriteRenderer.flipX = false;
currentAnimation = "Down";
animator.Play("Down");
}
if (angle < (225 + offset) && angle > (225 - offset))
{
spriteRenderer.flipX = true;
currentAnimation = "DownRight";
animator.Play("DownRight");
}
if (angle < (270 + offset) && angle > (270 - offset))
{
spriteRenderer.flipX = true;
currentAnimation = "Right";
animator.Play("Right");
}
if (angle < (315 + offset) && angle > (315 - offset))
{
spriteRenderer.flipX = true;
currentAnimation = "UpRight";
animator.Play("UpRight");
}
//
//Since our units are flat 2D sprites in a 3D environment, we need to rotate them so the front is always facing the camera.
//Get the camera's position and use Unity's LookAt Method so the unit faces the camera.
Vector3 position = Camera.main.transform.position;
position.y = unit.transform.position.y;
unit.transform.LookAt(position);
}



Comments