Skip to content

Commit

Permalink
[SOK-27] fix: Настроил сравнение с canvas
Browse files Browse the repository at this point in the history
  • Loading branch information
shamemask committed Sep 30, 2024
1 parent 4e0b9b3 commit ed29145
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 7 deletions.
13 changes: 10 additions & 3 deletions packages/client/src/components/Game/Game.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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)
Expand Down
11 changes: 7 additions & 4 deletions packages/client/src/components/Game/controls.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,14 +16,17 @@ export const handleKeyUp = (key: string) => {
export const updatePlayerMovement = (
player: Player,
setPlayer: React.Dispatch<React.SetStateAction<Player>>,
speedFactor: number
speedFactor: number,
canvasWidth: number,
canvasHeight: number
) => {
const speed = player.speed * speedFactor

setPlayer(prevPlayer => {
let newX = prevPlayer.x
let newY = prevPlayer.y

// Определение направления движения
if (keyMap['ArrowUp'] || keyMap['w'] || keyMap['ц']) {
newY -= speed
}
Expand All @@ -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 }
})
Expand Down

0 comments on commit ed29145

Please sign in to comment.