GGJ22/Engine/src/live/Entity.ts
2022-01-29 21:43:20 -08:00

87 lines
1.9 KiB
TypeScript

import * as planck from 'planck'
import { SpriteInstance } from '../shared/sprites'
import { WorldContext } from './World'
import { Zone } from './Zone'
export class Entity {
sprite: SpriteInstance
body?: planck.Body
velocity: [number, number] = [0, 0]
acceleration: number = 0.5
maxSpeed: number = 4
direction: number = 0
turnRate: number = 10
zones: Zone[] = []
contacts: Entity[] = []
constructor(ctor: string) {
this.sprite = new SpriteInstance(ctor)
}
update(delta: number, ctx?: WorldContext) {
this.sprite.update(delta)
}
get position(): [number, number] {
if (this.body) {
let p = this.body.getPosition()
return [p.x, p.y]
}
return [this.sprite.container.x, this.sprite.container.y]
}
get x(): number {
if (this.body) {
let p = this.body.getPosition()
return p.x
}
return this.sprite.container.x
}
set x(v: number) {
if (this.body) {
let p = this.body.getPosition()
this.body.setPosition(
planck.Vec2(
v,
p.y,
)
)
} else {
this.sprite.container.y = v
}
}
get y(): number {
if (this.body) {
let p = this.body.getPosition()
return p.y
}
return this.sprite.container.y
}
set y(v: number) {
if (this.body) {
let p = this.body.getPosition()
this.body.setPosition(
planck.Vec2(
p.x,
v,
)
)
} else {
this.sprite.container.y = v
}
}
addZoneContact(zone: Zone) {
if (this.zones.find(v=>v===zone)) return
this.zones.push(zone)
}
removeZoneContact(zone: Zone) {
this.zones = this.zones.filter(v=>v!==zone)
}
addEntityContact(entity: Entity) {
if (this.contacts.find(v=>v===entity)) return
this.contacts.push(entity)
}
removeEntityContact(entity: Entity) {
this.contacts = this.contacts.filter(v=>v!==entity)
}
}