123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293 |
- import * as CANNON from './cannon-es.js'
- export default class Entity {
- constructor(userId, playerColor) {
- this.id = userId
- this.color = playerColor
- this.radius = 4
- this.angle = 0
- this.thrustPower = 10
- this.body = new CANNON.Body({
- mass: 1, // kg
- position: new CANNON.Vec3(20, 20, 0),
- shape: new CANNON.Sphere(this.radius), //radius
- linearFactor: new CANNON.Vec3(1,1,0), //only move 2D
- })
- }
- attachToWorld(world){
- world.addBody(this.body)
- }
- getAngle(q) {
- /*
- https://stackoverflow.com/questions/5782658/extracting-yaw-from-a-quaternion
- */
- //yaw
- // return Math.atan2(2.0 * (q.y * q.z + q.w * q.x), q.w * q.w - q.x * q.x - q.y * q.y + q.z * q.z)
- // pitch
- // return Math.asin(-2.0 * (q.x * q.z - q.w * q.y))
- //roll
- return Math.atan2(2.0 * (q.x * q.y + q.w * q.z), q.w * q.w + q.x * q.x - q.y * q.y - q.z * q.z)
- }
- turnLeft() {
- this.angle += Math.PI / 16
- }
- turnRight() {
- this.angle -= Math.PI / 16
- }
- thrust() {
- let point = new CANNON.Vec3(this.body.position.x, this.body.position.y, this.body.position.z)
- let impulse = new CANNON.Vec3(this.thrustPower * Math.cos(this.angle), this.thrustPower * Math.sin(this.angle), 0)
- this.body.applyImpulse(impulse, point)
- }
- update() {
- this.body.quaternion.setFromAxisAngle(new CANNON.Vec3(0,0,1), this.angle)
- }
- worldEdgeWrap(worldBounds) {
- if(this.body.position.x >= worldBounds.width) {
- this.body.position.x -= worldBounds.width
- }
- if(this.body.position.x < 0) {
- this.body.position.x += worldBounds.width
- }
- if(this.body.position.y >= worldBounds.height) {
- this.body.position.y -= worldBounds.height
- }
- if(this.body.position.y < 0) {
- this.body.position.y += worldBounds.height
- }
- }
- draw(ctx) {
- ctx.save()
- ctx.translate(this.body.position.x, this.body.position.y)
- ctx.rotate(this.angle)
- ctx.fillStyle = this.color
- ctx.strokeStyle = this.color
- ctx.beginPath()
- ctx.arc(0, 0, this.radius, 0, 2 * Math.PI)
- ctx.closePath()
- ctx.fill()
- ctx.stroke()
- ctx.strokeStyle = "yellow"
- ctx.lineWidth = 1
- ctx.beginPath()
- ctx.moveTo(0,0)
- ctx.lineTo(4, 0)
- ctx.stroke()
- ctx.restore()
- }
- }
|