87 lines
2.2 KiB
TypeScript
Raw Normal View History

2022-12-01 22:26:41 +08:00
import { SpriteFrame } from "cc"
2022-12-04 22:10:30 +08:00
import { ApiMsgEnum, InputTypeEnum, strdecode } from "../Common"
2022-11-27 23:23:47 +08:00
const INDEX_REG = /\((\d+)\)/
const getNumberWithinString = (str: string) => parseInt(str.match(INDEX_REG)?.[1] || '0')
export const sortSpriteFrame = (spriteFrame: Array<SpriteFrame>) =>
spriteFrame.sort((a, b) => getNumberWithinString(a.name) - getNumberWithinString(b.name))
export const rad2Angle = (rad: number) => rad / Math.PI * 180
2022-12-04 22:10:30 +08:00
export const binaryDecode = (buffer: ArrayBuffer) => {
let index = 0
const view = new DataView(buffer)
const type = view.getUint8(index++)
if (type === ApiMsgEnum.MsgClientSync) {
const inputType = view.getUint8(index++)
if (inputType === InputTypeEnum.ActorMove) {
const id = view.getUint8(index++)
const directionX = view.getFloat32(index)
index += 4
const directionY = view.getFloat32(index)
index += 4
const dt = view.getFloat32(index)
index += 4
const msg = {
name: ApiMsgEnum.MsgClientSync,
data: {
type: InputTypeEnum.ActorMove,
id,
direction: {
x: directionX,
y: directionY,
},
dt
}
}
return msg
} else if (inputType === InputTypeEnum.WeaponShoot) {
const id = view.getUint8(index++)
const positionX = view.getFloat32(index)
index += 4
const positionY = view.getFloat32(index)
index += 4
const directionX = view.getFloat32(index)
index += 4
const directionY = view.getFloat32(index)
index += 4
const msg = {
name: ApiMsgEnum.MsgClientSync,
data: {
type: InputTypeEnum.WeaponShoot,
id,
position: {
x: positionX,
y: positionY,
},
direction: {
x: directionX,
y: directionY,
},
}
}
return msg
} else {
const dt = view.getFloat32(index)
index += 4
const msg = {
name: ApiMsgEnum.MsgClientSync,
data: {
type: InputTypeEnum.TimePast,
dt,
}
}
return msg
}
} else {
return {
name: type,
data: JSON.parse(strdecode(new Uint8Array(buffer.slice(1))))
}
}
}