1
0
forked from noxious/server

Joining, leaving rooms and teleporting works again + refactor

This commit is contained in:
2025-01-01 04:46:00 +01:00
parent 30b2028bd8
commit 495e9f192e
5 changed files with 175 additions and 97 deletions

View File

@ -1,6 +1,6 @@
import { Character } from '#entities/character'
import TeleportService from '#services/teleportService'
import ZoneManager from '#managers/zoneManager'
import Logger, { LoggerType } from '#application/logger'
import SocketManager from '#managers/socketManager'
class ZoneCharacter {
@ -13,44 +13,44 @@ class ZoneCharacter {
}
public async savePosition() {
await this.character.setPositionX(this.character.positionX).setPositionY(this.character.positionY).setRotation(this.character.rotation).setZone(this.character.zone).update()
await this.character
.setPositionX(this.character.positionX)
.setPositionY(this.character.positionY)
.setRotation(this.character.rotation)
.setZone(this.character.zone)
.update()
}
public async teleport(zoneId: number, targetX: number, targetY: number): Promise<void> {
const io = SocketManager.getIO()
const socket = SocketManager.getSocketByCharacterId(this.character.id)
const zone = ZoneManager.getZoneById(zoneId)?.getZone()
const logger = Logger.type(LoggerType.APP)
console.log('teleporting')
if (!socket) {
logger.error('zone:character:move error: Socket not found')
return
}
if (!zone) {
logger.error('zone:character:move error: Zone not found')
return
}
// Let other clients know of new character
io.to(zone.id.toString()).emit('zone:character:join', 'ewaewa')
// Update zoneCharacter properties
this.currentPath = null
this.isMoving = false
// Update local character object
await this.character.setPositionX(targetX).setPositionY(targetY).setRotation(this.character.rotation).setZone(zone).update()
// Emit teleport event
socket.emit('zone:character:teleport', {
zone,
characters: ZoneManager.getZoneById(zone.id)?.getCharactersInZone()
await TeleportService.teleportCharacter(this.character.id, {
targetZoneId: zoneId,
targetX,
targetY
})
}
console.log('teleported')
public async disconnect(socket: Socket, io: Server): Promise<void> {
try {
// Stop any movement and save final position
this.isMoving = false
this.currentPath = null
await this.savePosition()
// Leave zone and remove from manager
if (this.character.zone) {
socket.leave(this.character.zone.id.toString())
ZoneManager.removeCharacter(this.character.id)
// Notify zone players
io.in(this.character.zone.id.toString()).emit('zone:character:leave', this.character.id)
}
// Notify all players
io.emit('character:disconnect', this.character.id)
} catch (error) {
console.error(`Error disconnecting character ${this.character.id}:`, error)
}
}
}
export default ZoneCharacter
export default ZoneCharacter