From ed291458dd9bd70c2befdb3eeb8ea431ccb8cd63 Mon Sep 17 00:00:00 2001 From: Daniil <77277774+shamemask@users.noreply.github.com> Date: Mon, 30 Sep 2024 19:15:41 +0300 Subject: [PATCH] =?UTF-8?q?[SOK-27]=20fix:=20=D0=9D=D0=B0=D1=81=D1=82?= =?UTF-8?q?=D1=80=D0=BE=D0=B8=D0=BB=20=D1=81=D1=80=D0=B0=D0=B2=D0=BD=D0=B5?= =?UTF-8?q?=D0=BD=D0=B8=D0=B5=20=D1=81=20canvas?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- packages/client/src/components/Game/Game.tsx | 13 ++++++++++--- packages/client/src/components/Game/controls.tsx | 11 +++++++---- 2 files changed, 17 insertions(+), 7 deletions(-) diff --git a/packages/client/src/components/Game/Game.tsx b/packages/client/src/components/Game/Game.tsx index c9fcecc..d516d12 100644 --- a/packages/client/src/components/Game/Game.tsx +++ b/packages/client/src/components/Game/Game.tsx @@ -52,7 +52,15 @@ export const Game: React.FC = () => { const elapsed = timestamp - lastTimestamp setDelay(elapsed) } - updatePlayerMovement(player, setPlayer, speedFactor) + const canvas = getCanvas() + if (!canvas) return + updatePlayerMovement( + player, + setPlayer, + speedFactor, + canvas.width, + canvas.height + ) gameLoop( timestamp, context, @@ -102,8 +110,7 @@ export const Game: React.FC = () => { useEffect(() => { if (gameStarted && !isPaused) { - const canvas = canvasRef.current - context = canvas?.getContext('2d') + context = getContext() if (context) { requestAnimationFrame(loop) diff --git a/packages/client/src/components/Game/controls.tsx b/packages/client/src/components/Game/controls.tsx index 1473555..3bc2e88 100644 --- a/packages/client/src/components/Game/controls.tsx +++ b/packages/client/src/components/Game/controls.tsx @@ -16,7 +16,9 @@ export const handleKeyUp = (key: string) => { export const updatePlayerMovement = ( player: Player, setPlayer: React.Dispatch>, - speedFactor: number + speedFactor: number, + canvasWidth: number, + canvasHeight: number ) => { const speed = player.speed * speedFactor @@ -24,6 +26,7 @@ export const updatePlayerMovement = ( let newX = prevPlayer.x let newY = prevPlayer.y + // Определение направления движения if (keyMap['ArrowUp'] || keyMap['w'] || keyMap['ц']) { newY -= speed } @@ -37,9 +40,9 @@ export const updatePlayerMovement = ( newX += speed } - // Ограничение движения по краям экрана - newX = Math.max(0, Math.min(newX, window.innerWidth - prevPlayer.width)) - newY = Math.max(0, Math.min(newY, window.innerHeight - prevPlayer.height)) + // Ограничение движения по краям canvas + newX = Math.max(0, Math.min(newX, canvasWidth - prevPlayer.width)) + newY = Math.max(0, Math.min(newY, canvasHeight - prevPlayer.height)) return { ...prevPlayer, x: newX, y: newY } })