- Home /
How To Detect Player Movement
Hello, I have a player with a character controller, and I'm trying to detect if the player is moving using an if statement:
if(//detect player movement//)
{
// do something
}
else
{
//do something
}
Also, I am trying to do it without using velocity.magnitude > 0
. If anyone could help, it would be GREATLY appreciated.
Answer by Zaeran · Sep 18, 2020 at 05:24 PM
Create a vector3 variable and use it to store the position of the player at the end of your update loop. Then you can check if the current position is equal to the position last frame to know if movement has occurred.
Vector3 lastPos;
void Update ()
{
if(player.transform.position != lastPos)
{
//Player has moved
}
else
{
//Player has not moved
}
lastPos = player.transform.position
}
@Zaeran , Just looking at this script and reading it seems like it makes sense and would work. But I am getting errors saying that player isn't defined and I don't think that my Vector3 is working ( it's not turning purple).
Hey, I know it's been almost a year but to answer your question, you need to make some sort of variable that is named "player" and since we are checking if it's moving that variable must be a physical object of some sort. You can put "public GameObject player" at the top of your script and it'll fix the error.
If the script is a component of the game object you're trying to manipulate, replace "player" with "this". If it's separate, create a GameObject
variable above your method, navigate to your script in the Inspector, and drag in your object.