I create this simple example script to animate a player position using a simple setInterval function but impossible to make it works..
Everytime it go into the interval function the playerPos is back to is initial value..
import React, { useEffect, useState } from 'react';
const App = () => {
let [playerPos, setPlayerPos] = useState({x:128, y:128})
useEffect(() => {
setInterval(() => {
console.log(`Current player pos ${JSON.stringify(playerPos)}`);
setPlayerPos({x:128, y:playerPos.y + 10});
}, 1000);
}, []);
return <div style={{position: "absolute", top: `${playerPos.x}px`, left: `${playerPos.y}px`}}></div>
}
Strangely, my console only showing:
Current player pos {"x":128,"y":128}
Current player pos {"x":128,"y":128}
Current player pos {"x":128,"y":128}
...
What did I misunderstood in hooks and effects ??!