- Home /
Having problem with detecting movement
Hey there everybody :D so I have a problem with this code.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class AnimationPlay : MonoBehaviour {
private Animator animator;
private Vector3 oldPos,newPos;
void Start()
{
oldPos = GameObject.Find ("FPSController").transform.position;
animator = gameObject.GetComponent<Animator> ();
}
void Update ()
{
newPos = GameObject.Find ("FPSController").transform.position;
if (newPos != oldPos)
{
animator.SetBool ("Moving", true);
}
else if (newPos == oldPos)
{
animator.SetBool ("Moving", false);
}
oldPos = GameObject.Find ("FPSController").transform.position;
}
}
I'm trying to detect if the game object "FPSController" is moving by using transform.position and see if it's position has changed from the last time and if it is moving, I will set the Boolean "Moving" true which I created in an animator for game object "Player" (("Player" is a child of "FPSController")) and then it should play walking animation that i made in blender. when my character moves, the Boolean keeps flickering true and false and also the walking animation gets too long to play like 6 or 7 seconds after player moves. I have no idea what is causing this, cuz in theory it should work... in the picture "FPSController" is moving, the "Moving" Boolean is flickering, and the Standing animation is playing instead of walking animatin...
am i missing something? and thanks for your time :)
You could use the difference between the two states and then magnitude it to get the velocity. You can then set the walking animation while the velocity is greater than a threshold (eg 0.05). But it is a bit of a hack. Why dont you directly trigger the animation from within the FPSController?
i tried using the velocity and it didn't change the result and about triggering the animation in FPScontroller, you mean like animator.play()?!
Similar to your "$$anonymous$$oving" boolean you can create a Trigger. Then you can assign this trigger as a transition condition from Standing to Walking. You force this transition by calling Animation.SetTrigger() in the FPSController, e.g. directly when you apply force/motion to your character.
Answer by Spacejet13 · Jan 23, 2019 at 01:35 AM
Use the same bool variables you have used to determine whether the character is moving (if player is pressing the 'move' button) and making him move in the game. Just set the animation to change if player presses the button that moves the character.
.
EDIT:
Your animation is not transitioning!! look in the inspector window of the image you posted. the standing and walking animations should not overlap each other! it should transition from standing to walking