Prevent walk through obstacles

This commit is contained in:
2024-08-19 18:00:06 +02:00
parent 5ce844c919
commit 910d8ad8f1
2 changed files with 18 additions and 13 deletions

View File

@ -44,6 +44,13 @@ export default function setupCharacterMove(socket: TSocket, io: Server) {
console.log('Pathfinding from', start, 'to', end)
console.log('Grid dimensions:', grid.length, 'x', grid[0].length)
// Check if the destination is an obstacle
if (isObstacle(end, grid)) {
console.log('character:move error', 'Destination is an obstacle')
socket.emit('character:moveError', 'Destination is an obstacle')
return
}
const path = AStar.findPath(start, end, grid)
if (path.length > 0) {
@ -71,7 +78,7 @@ async function moveAlongPath(socket: TSocket, io: Server, path: Node[], grid: nu
const totalSteps = path.length
const updateInterval = 50 // milliseconds between updates
for (let step = 0; step < totalSteps; step++) {
for (let step = 0; step < totalSteps - 1; step++) {
if (characterMoveTokens.get(socket.character.id) !== moveToken) {
console.log('Movement cancelled for character', socket.character.id)
return
@ -87,16 +94,14 @@ async function moveAlongPath(socket: TSocket, io: Server, path: Node[], grid: nu
}
const progress = (Date.now() - startTime) / stepDuration
const currentPosition = interpolatePosition(path[step], path[step + 1] || path[step], progress)
const currentPosition = interpolatePosition(path[step], path[step + 1], progress)
if (isObstacle(currentPosition, grid)) {
console.log('Obstacle encountered at', currentPosition)
break
}
const rotation = step < totalSteps - 1
? Rotation.calculate(path[step].x, path[step].y, path[step + 1].x, path[step + 1].y)
: socket.character.rotation
const rotation = Rotation.calculate(path[step].x, path[step].y, path[step + 1].x, path[step + 1].y)
await updateCharacterPosition(socket.character, currentPosition.x, currentPosition.y, rotation)
@ -122,7 +127,7 @@ function interpolatePosition(start: Node, end: Node, progress: number): Node {
}
}
function isObstacle(position: Node, grid: number[][]): boolean {
function isObstacle(position: { x: number; y: number }, grid: number[][]): boolean {
const x = Math.floor(position.x)
const y = Math.floor(position.y)
return grid[y] && grid[y][x] === 1