1
0
forked from noxious/server

Stop current pathfinding task if a new one is initialized to prevent glitches

This commit is contained in:
Dennis Postma 2024-08-03 18:31:41 +02:00
parent 535bb36edc
commit eb4cbb5e9e

View File

@ -11,6 +11,9 @@ interface SocketResponse {
position_y: number
}
// Add a cancellation token
let currentMoveToken: Symbol | null = null
export default function setupCharacterMove(socket: TSocket, io: Server) {
socket.on('character:move', async (data: SocketResponse) => {
try {
@ -21,6 +24,10 @@ export default function setupCharacterMove(socket: TSocket, io: Server) {
return
}
// Cancel any ongoing movement
currentMoveToken = Symbol('moveToken')
const moveToken = currentMoveToken
const grid = await ZoneManager.getGrid(socket.character.zoneId)
if (grid.length === 0) {
@ -37,11 +44,13 @@ export default function setupCharacterMove(socket: TSocket, io: Server) {
socket.character.isMoving = true
io.in(socket.character.zoneId.toString()).emit('character:moved', socket.character)
try {
await moveAlongPath(socket, io, path, grid)
await moveAlongPath(socket, io, path, grid, moveToken)
} finally {
if (currentMoveToken === moveToken) {
socket.character.isMoving = false
io.in(socket.character.zoneId.toString()).emit('character:moved', socket.character)
}
}
} else {
console.log('character:move error', 'No valid path found')
}
@ -55,10 +64,16 @@ export default function setupCharacterMove(socket: TSocket, io: Server) {
})
}
async function moveAlongPath(socket: TSocket, io: Server, path: Node[], grid: number[][]) {
async function moveAlongPath(socket: TSocket, io: Server, path: Node[], grid: number[][], moveToken: Symbol) {
if (!socket.character) return
for (let i = 0; i < path.length; i++) {
// Check if this movement has been cancelled
if (currentMoveToken !== moveToken) {
console.log('Movement cancelled, stopping current path')
return
}
const position = path[i]
if (isObstacle(position, grid)) {
console.log('Obstacle encountered at', position)