Update the state of of an object dynamically in React

I am try to toggle the state of an object tha has two values un: 'CharacterArmature|Run' and stop: "CharacterArmature|Idle" stored in a animation useState hook based on the result of a boolean defined in another component as a isMoving useState of which initial value is set to false. I can change the value as true when a key is pressed but I can not switch it back to the original value which is false when the key it is not pressed.
This is my component where isMoving state is defined and then is passed to the Character component as prop:

const Controller = () => {

const [isMoving, setIsMoving] = useState(false)

// here the state of isMoving is updated 
 if(rightPressed && linvel.x < MAX_VEL) {
        impulse.x += MOVEMENT_SPEED
        changeRotation = true
        setIsMoving(true)
// rest of the controller events
return(
//...
   <Character setIsMoving={isMoving}/>
//...
)
}

and the Character component receives it like this:


function Character({setIsMoving}) {
  const { actions } = useAnimations(animations, group)
//this is the object that I want to toggle after the setIsMoving value 
  const [animation, setAnimations] = useState({ 
// these are the values that i am trying to toggle 
    run: 'CharacterArmature|Run',
    stop: "CharacterArmature|Idle"
})

// and i have it like this 
 useEffect(() => {
    if(setIsMoving){ 
    actions[animation.run].reset().fadeIn(0.5).play();
    
    }else  {
        actions[animation.stop].reset().fadeIn(0.5).play();
       
    }
    // return () => actions[animation].fadeOut(0.5);
  }, [animation, setIsMoving]);


So I have tried to change the value if any of the controller events are not pressed like this

if (
      !jumpPressed &&
      !rightPressed &&
      !leftPressed &&
      !forwardPressed &&
      !backPressed
    ) {
      setIsMoving(false);
    }

but that did not work the animation does not update its value. Is there another way I could change its value dynamically based on the isMoving state?

  • So what is your issue? You say first “I can not switch [isMoving] back to the original value” but later “Is there another way I could change [animation] value dynamically based on the isMoving state?

    – 

Leave a Comment