I have been trying to create an animation so that i can control the block with my arrow key and spacebar on my keyboard, I have managed to get the jump working by changing the velocity y figures,however, i am still struggling to move the box to the left and right, I have tried to set the state to true when I have my key down so that when its true it will set my velocity x up and the block will keep going right until i key up, it will return back false and set the velocity x back to 0, but for some reason, this is not working, here are my codes:
const gravity = 4.5;
const Canvas = () => {
const { innerWidth: innerwidth, innerHeight: innerheight } = window;
const canvasRef = useRef();
const [position, setPosition] = useState({ x: 100, y: 100 });
const [size, setSize] = useState({ width: 30, height: 30 });
const [velocity, setVelocity] = useState({ x: 0, y: 0 });
const [pressRight, setPressRight]= useState(false)
const [pressLeft, setPressLeft]= useState(false)
const draw = useCallback((context) => {
context.fillStyle = 'red';
context.fillRect(position.x, position.y, size.width, size.height);
}, [position, size]);
const update = useCallback((context, canvas) => {
draw(context)
setPosition({ x: position.x, y: position.y += velocity.y })
if (position.y + size.height + velocity.y <= canvas.height) {
setVelocity({ x: velocity.x, y: velocity.y += gravity })
} else {
setVelocity({ x:velocity.x, y: velocity.y = 0 })
}
}, [position, size, velocity]);
const animate = (context, width, height, canvas) => {
requestAnimationFrame(() => {
animate(context, width, height, canvas);
});
context.clearRect(0, 0, width, height);
update(context, canvas);
if(!pressRight){
setVelocity({ x: velocity.x = 0 , y: velocity.y})
console.log("let go")
}else{
setVelocity({ x: velocity.x += 5 , y: velocity.y});
console.log("pressed")
}
}
useEffect(() => {
const canvas = canvasRef.current;
const context = canvas.getContext('2d');
canvas.width= innerwidth - 10;
canvas.height= innerheight - 10;
animate(context, canvas.width, canvas.height, canvas)
}, []);
const handleKeyDown = useCallback(({ key }) => {
switch (key) {
case 'ArrowLeft':
break;
case 'ArrowRight':
setPressRight(true)
break;
case ' ': // Spacebar
setVelocity({ x: velocity.x, y: velocity.y -= 50 });
break
default:
console.log(`Unknown key: ${key}`);
}
}, []);
const handleKeyUp = useCallback(({ key }) => {
switch (key) {
case 'ArrowLeft':
break;
case 'ArrowRight':
setPressRight(false)
break;
case ' ':
break
default:
console.log(`Unknown key: ${key}`);
}
}, []);
return (
<canvas
ref={canvasRef}
tabIndex={-1}
onKeyDown={handleKeyDown}
onKeyUp={handleKeyUp}
/>
);
};
export default Canvas;
Would appreciate any help or suggestion.