- Home /
Need help with sprite rotation
My game is a 2D space game. You have to manipulate gravity to keep asteroids away from earth, and they all have faces. My trouble is having the face of the asteroid always looking towards the direction it is going without flipping upsidedown. I've been going at this since yesterday and can not find a post or think of an answer. Also if you see anything that could be better, please do tell me! I want to learn as much as possible. Here is my code:
using UnityEngine;
public class AsteroidFace : MonoBehaviour
{
public Sprite[] sprites;
SpriteRenderer spriteRenderer;
Rigidbody2D rbParent;
bool isUpsidedown = true;
void Start()
{
spriteRenderer = GetComponent<SpriteRenderer>();
spriteRenderer.sprite = sprites[Random.Range(0, sprites.Length)];
rbParent = GetComponentInParent<Rigidbody2D>();
}
void Update()
{
Vector2 moveDirection = rbParent.velocity;
if (moveDirection != Vector2.zero)
{
float angle = Mathf.Atan2(moveDirection.y, moveDirection.x) * Mathf.Rad2Deg;
if (angle >= 90 && isUpsidedown || angle <= -90 && isUpsidedown)
{
spriteRenderer.flipY = true;
isUpsidedown = false;
} else if(angle <= 90 && !isUpsidedown || angle >= -90 && !isUpsidedown)
{
spriteRenderer.flipY = false;
isUpsidedown = true;
}
Debug.Log(angle);
transform.rotation = Quaternion.AngleAxis(angle, Vector3.forward);
}
}
}
Comment