Stop current pathfinding task if a new one is initialized to prevent glitches
This commit is contained in:
parent
535bb36edc
commit
eb4cbb5e9e
@ -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,10 +44,12 @@ 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 {
|
||||
socket.character.isMoving = false
|
||||
io.in(socket.character.zoneId.toString()).emit('character:moved', socket.character)
|
||||
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)
|
||||
|
Loading…
x
Reference in New Issue
Block a user