- Home /
How to know if my player is not moving?
I have the next script for my player's movement. It manages a simple 2D top down movement and it's animation.
public class PlayerScript: MonoBehaviour {
public float speed;
public Animator animator;
// The rigid body has to be kinematic in order to not fall down because of the gravity.
Rigidbody2D rigidBody;
Vector2 moveVelocity;
void Start() {
rigidBody = GetComponent < Rigidbody2D > ();
}
void Update() {
Vector2 moveInput = new Vector2(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical"));
moveVelocity = moveInput.normalized * speed;
animator.SetFloat("Horizontal", moveInput.x);
animator.SetFloat("Vertical", moveInput.y);
animator.SetFloat("Speed", moveInput.sqrMagnitude);
}
private void FixedUpdate() {
rigidBody.MovePosition(rigidBody.position + moveVelocity * Time.fixedDeltaTime);
}
}
Is there a way to know if the player is not moving? This include when the player not moves because is colliding with a collider.
Answer by CodesCove · Sep 20, 2020 at 10:35 PM
I'm not sure I got your intention right but here is method to check if object is moving regardless the reason/type of movement. So the simplest thing would be to just check the transform.position between the fixed update. Of course the resolution is fixed frame but if this is enough then this should be ok.
This is individual component example but easily implementable to your code:
public class Testing : MonoBehaviour
{
public GameObject movingGO;
public bool isMoving;
public Vector3 lastPos;
public void FixedUpdate()
{
if (movingGO.transform.position.Equals(lastPos)) isMoving = false; else isMoving = true;
lastPos = movingGO.transform.position;
}
}
Answer by mbro514 · Sep 20, 2020 at 12:48 AM
if (moveInput.sqrMagnitude == 0)
Technically, you could do moveInput.magnitude, but it takes a lot longer and there's no benefit to using it in this case.
This work well but don't work when the user is not moving because is colliding with something.