Sprite facing dash direction

So I have a script which allows me to dash in eight directions, up, right/up, right, right/down and so on. What I want to do now is have it so that my sprite rotates and faces the direction im dashing. I have play around a bit with

float angle = Mathf.Atan2(dashDirection.x, dashDirection.y) * Mathf.Rad2Deg;
transform.rotation = Quaternion.AngleAxis(angle, Vector3.forward);

I only got it to work on the side/up directions but no the other ones. Anyone who has some insight in this field? Thanks!

My 2 cents:
1: Slightly unrelated but if you have a character that has a sprite and is not symmetrical then you might want to flip the sprite when facing the opposite way to which the initial sprite is set. Eg. if the sprite is looking rightwards then when dashing to the left you want to make negative the x scale on the game object with the sprite to make the sprite “face leftwards”. If you go along with this then the rotation would also have to be slightly altered keeping the “flip” in mind.
2: If you’ve seen how tan works as far as I’m aware the tan will only give you values between -90 and 90. So that may be why certain directions work for you but not for some other directions.

My own method (which definitely someone could improve on) is something liek this:

// moveDir is the direction the character is moving.
// the facingLeft boolean is for keeping track of which way to flip the sprite as I use the method I mentioned in my 1st point above.
// when not moving (moveDir == 0) we just return current rotation angle.
//max rotation in my case was 30degrees. You could just make it 90 for full rotation I think.

float angle =  moveDir.x == 0 ? (moveDir.y == 0 ? transform.rotation.z : (moveDir.y > 0 ? (facingLeft == true ? -maxRotation : maxRotation) : (facingLeft == true ? maxRotation : -maxRotation))) : 180f * Mathf.Atan(moveDir.y / moveDir.x) / Mathf.PI;
angle = Mathf.Sign(angle) * Mathf.Min(Mathf.Abs(angle), maxRotation);
transform.rotation = Quaternion.Euler(0f, 0f, angle);

i’ll try give you a cleaner looking one. hang on :slight_smile:

ok found much cleaner solution for simple rotation situation w.r.t direction you want to face. Just use the following:

//the input is the direction that you want to be facing.
void spin(Vector2 input) {
	if (input.magnitude == 0) return;
	//signedangle returns a -180 to 180 closest angle between 2 vector2's. we can use this directly as the angle for rotation as we are setting the rotation.
	//we use the upwards (0x, 1y) direction in 2D for reference in angle calculation.
	float angle = Vector2.SignedAngle(new Vector2 (0f, 1f), input);
	transform.rotation = Quaternion.AngleAxis(angle, Vector3.forward);