86 lines
2.5 KiB
TypeScript
Raw Normal View History

2022-12-01 22:26:41 +08:00
import { _decorator } from 'cc'
2022-11-27 23:23:47 +08:00
import { EntityManager } from '../../Base/EntityManager'
2022-12-03 20:06:57 +08:00
import { EntityTypeEnum, IBullet, IVec2 } from '../../Common'
import { EntityStateEnum, EventEnum } from '../../Enum'
import DataManager from '../../Global/DataManager'
2022-11-27 23:23:47 +08:00
import EventManager from '../../Global/EventManager'
import ObjectPoolManager from '../../Global/ObjectPoolManager'
import { rad2Angle } from '../../Utils'
import { ExplosionManager } from '../Explosion/ExplosionManager'
import { BulletStateMachine } from './BulletStateMachine'
2022-12-01 22:26:41 +08:00
const { ccclass } = _decorator
2022-11-27 23:23:47 +08:00
@ccclass('BulletManager')
2022-12-03 20:06:57 +08:00
export class BulletManager extends EntityManager implements IBullet {
2022-11-27 23:23:47 +08:00
//静态数据
2022-12-01 22:26:41 +08:00
id: number
owner: number
type: EntityTypeEnum
2022-11-27 23:23:47 +08:00
//动态数据
position: IVec2
direction: IVec2
private angle: number
init({ id, owner, type }: IBullet) {
this.id = id
this.owner = owner
this.type = type
this.fsm = this.addComponent(BulletStateMachine)
this.fsm.init(type)
this.state = EntityStateEnum.Idle
this.node.active = false
2022-12-01 22:26:41 +08:00
EventManager.Instance.on(EventEnum.ExplosionBorn, this.handleExplosion, this)
2022-11-27 23:23:47 +08:00
}
handleExplosion(id: number, { x, y }: IVec2) {
if (this.id !== id) {
return
}
2022-12-01 22:26:41 +08:00
const explosion = ObjectPoolManager.Instance.get(EntityTypeEnum.Explosion)
2022-11-27 23:23:47 +08:00
const explosionManager = explosion.getComponent(ExplosionManager) || explosion.addComponent(ExplosionManager)
explosionManager.init(EntityTypeEnum.Explosion, {
x, y,
})
2022-12-01 22:26:41 +08:00
EventManager.Instance.off(EventEnum.ExplosionBorn, this.handleExplosion, this)
ObjectPoolManager.Instance.ret(this.node)
DataManager.Instance.bulletMap.delete(this.id)
this.angle = undefined
2022-11-27 23:23:47 +08:00
}
render(data: IBullet) {
this.node.active = true
this.renderPosition(data)
this.renderDirection(data)
}
renderPosition(data: IBullet) {
this.node.setPosition(data.position.x, data.position.y)
}
renderDirection(data: IBullet) {
if (this.angle === undefined) {
const { x, y } = data.direction
const side = Math.sqrt(x * x + y * y)
this.angle = x > 0 ? rad2Angle(Math.asin(y / side)) : rad2Angle(Math.asin(- y / side)) + 180
}
this.node.setRotationFromEuler(0, 0, this.angle)
// let angle: number, sign: number
// if (x !== 0) {
// angle = x > 0 ? rad2Angle(Math.atan(y / x)) : rad2Angle(Math.atan(-y / x)) + 180
// sign = x > 0 ? 1 : -1
// } else {
// angle = rad2Angle(Math.PI / 2)
// sign = y > 0 ? 1 : -1
// }
// this.node.setRotationFromEuler(0, 0, sign * angle)
}
}