Skip to content

Commit

Permalink
[SOK-27] fix: Настроил движение и проверку колизии с объектом в одной…
Browse files Browse the repository at this point in the history
… функции
  • Loading branch information
shamemask committed Sep 30, 2024
1 parent ed29145 commit 959c1b4
Show file tree
Hide file tree
Showing 5 changed files with 46 additions and 27 deletions.
14 changes: 8 additions & 6 deletions packages/client/src/components/Game/Game.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,10 @@ import {
handleKeyUp,
updatePlayerMovement,
} from '@/components/Game/controls'
import { Obstacle } from '@/components/Game/gameTypes'
import { ControlsProps, Obstacle } from '@/components/Game/gameTypes'
import { initializeObstacle } from '@/components/Game/obstacle'

const speedFactor = 0.3
const speedFactor = 1
const livesUse = 3

export const Game: React.FC = () => {
Expand Down Expand Up @@ -54,13 +54,15 @@ export const Game: React.FC = () => {
}
const canvas = getCanvas()
if (!canvas) return
updatePlayerMovement(
const moveProps: ControlsProps = {
player,
setPlayer,
speedFactor,
canvas.width,
canvas.height
)
obstacles,
canvasWidth: canvas.width,
canvasHeight: canvas.height,
}
updatePlayerMovement(moveProps)
gameLoop(
timestamp,
context,
Expand Down
34 changes: 20 additions & 14 deletions packages/client/src/components/Game/controls.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { KeyMap, Player } from '@/components/Game/gameTypes'
import { ControlsProps, KeyMap } from '@/components/Game/gameTypes'
import { detectCollision } from '@/components/Game/player'

const keyMap: KeyMap = {}

Expand All @@ -13,16 +14,10 @@ export const handleKeyUp = (key: string) => {
}

// Функция для обновления позиции игрока на основе нажатых клавиш
export const updatePlayerMovement = (
player: Player,
setPlayer: React.Dispatch<React.SetStateAction<Player>>,
speedFactor: number,
canvasWidth: number,
canvasHeight: number
) => {
const speed = player.speed * speedFactor

setPlayer(prevPlayer => {
export const updatePlayerMovement = (props: ControlsProps) => {
const speed = props.player.speed * props.speedFactor

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

Expand All @@ -40,9 +35,20 @@ export const updatePlayerMovement = (
newX += speed
}

// Ограничение движения по краям canvas
newX = Math.max(0, Math.min(newX, canvasWidth - prevPlayer.width))
newY = Math.max(0, Math.min(newY, canvasHeight - prevPlayer.height))
// Обработка столкновений с препятствиями
props.obstacles.forEach(obstacle => {
if (detectCollision({ ...prevPlayer, x: newX, y: newY }, obstacle)) {
newX = prevPlayer.x
newY = prevPlayer.y
} else {
// Ограничение движения по краям canvas
newX = Math.max(0, Math.min(newX, props.canvasWidth - prevPlayer.width))
newY = Math.max(
0,
Math.min(newY, props.canvasHeight - prevPlayer.height)
)
}
})

return { ...prevPlayer, x: newX, y: newY }
})
Expand Down
9 changes: 4 additions & 5 deletions packages/client/src/components/Game/gameLoop.tsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,4 @@
import {
handlePlayerHit,
resetPlayerPosition,
updatePlayerPosition,
} from './player'
import { handlePlayerHit, resetPlayerPosition } from './player'
import {
updateEnemyPositions,
respawnEnemies,
Expand All @@ -23,6 +19,9 @@ import { Enemy, Obstacle, Player } from '@/components/Game/gameTypes'
* @param lives - Текущее количество жизней игрока.
* @param setLives - Функция для изменения количества жизней игрока.
* @param speedFactor - Коэффициент скорости.
* @param handleGameOver - Обработчик события окончания игры.
* @param isPaused - Флаг паузы.
* @param isGameOver - Флаг окончания игры.
*/
export const gameLoop = (
timestamp: number,
Expand Down
9 changes: 9 additions & 0 deletions packages/client/src/components/Game/gameTypes.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -26,3 +26,12 @@ export interface Obstacle {
export interface KeyMap {
[key: string]: boolean
}

export interface ControlsProps {
player: Player
setPlayer: React.Dispatch<React.SetStateAction<Player>>
speedFactor: number
obstacles: Obstacle[]
canvasWidth: number
canvasHeight: number
}
7 changes: 5 additions & 2 deletions packages/client/src/components/Game/player.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import { respawnEnemies } from '@/components/Game/enemy'
import { Enemy, Obstacle, Player } from '@/components/Game/gameTypes'

export const initializePlayer = () => ({
Expand All @@ -10,7 +9,10 @@ export const initializePlayer = () => ({
direction: { x: 0, y: 0 },
})

const detectCollision = (player: Player, obstacle: Obstacle): boolean => {
export const detectCollision = (
player: Player,
obstacle: Obstacle
): boolean => {
return (
player.x < obstacle.x + obstacle.width &&
player.x + player.width > obstacle.x &&
Expand Down Expand Up @@ -50,6 +52,7 @@ export const resetPlayerPosition = (

/**
* Функция для обработки столкновения игрока с врагом.
* @param setPlayer - Функция для обновления состояния игрока.
* @param setLives - Функция для изменения количества жизней игрока.
* @param resetPlayerPosition - Функция для сброса позиции игрока.
* @param respawnEnemies - Функция для респауна врагов.
Expand Down

0 comments on commit 959c1b4

Please sign in to comment.