I am trying to make a top down game with movement like in the game Binding of Isaac. I want my player to move all 4 directions facing one way, but when he shoots he faces the direction of where he is shooting, not the direction he is moving towards. I can figure most parts out, but I am not sure how to detect when he is moving in ANY direction so I can set a float “speed” to how fast he is moving and make it in the player animator controller if the speed is greater than 0.1 he will play a moving animation. I know I haven’t explained it very well, so I’ll just say I am trying to figure out how to set a float “speed” to however fast the player is moving, and it doesn’t matter what direction. Anyone have any answers?
Thanks!
You may check the direction of a Rigidbody2D by checking its velocity.
ThisRigidbody2D.velocity; //catch the velocity, as a vector
ThisRigidbody2D.velocity.magnitude; //calculate the speed, always equal or more than 0
To let the trasform follow the rigidbody you may apply this:
[RequireComponent(typeof(Rigidbody2D))]
public class Rigidbody2DLookAt : MonoBehaviour
{
//to decide the minimal speed, if the rigidbody is moving slower than that we stop
public float speedThreshold = 0.1f;
//the offset if you need to adjust the rotation
public float offset = 90f;
//the rigidbody
private Rigidbody2D _rigidbody2D;
//cache the rigidbody at start (or awake)
private void Start() { _rigidbody2D = GetComponent<Rigidbody2D>(); }
private void Update()
{
//gets the velocity as a vector
var velocity = _rigidbody2D.velocity;
//stops following the rigidbody rotation if 'moving too slow
if (velocity.magnitude <= speedThreshold) return;
//calculate the angle and rotate the transform accordingly
var angle = Mathf.Atan2(velocity.y, velocity.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.Euler(new Vector3(0, 0, angle + offset));
}
}