Entity.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. import * as CANNON from './cannon-es.js'
  2. export default class Entity {
  3. constructor(userId, playerColor) {
  4. this.id = userId
  5. this.color = playerColor
  6. this.radius = 4
  7. this.angle = 0
  8. this.thrustPower = 10
  9. this.body = new CANNON.Body({
  10. mass: 1, // kg
  11. position: new CANNON.Vec3(20, 20, 0),
  12. shape: new CANNON.Sphere(this.radius), //radius
  13. linearFactor: new CANNON.Vec3(1,1,0), //only move 2D
  14. })
  15. }
  16. attachToWorld(world){
  17. world.addBody(this.body)
  18. }
  19. getAngle(q) {
  20. /*
  21. https://stackoverflow.com/questions/5782658/extracting-yaw-from-a-quaternion
  22. */
  23. //yaw
  24. // 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)
  25. // pitch
  26. // return Math.asin(-2.0 * (q.x * q.z - q.w * q.y))
  27. //roll
  28. 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)
  29. }
  30. turnLeft() {
  31. this.angle += Math.PI / 16
  32. }
  33. turnRight() {
  34. this.angle -= Math.PI / 16
  35. }
  36. thrust() {
  37. let point = new CANNON.Vec3(this.body.position.x, this.body.position.y, this.body.position.z)
  38. let impulse = new CANNON.Vec3(this.thrustPower * Math.cos(this.angle), this.thrustPower * Math.sin(this.angle), 0)
  39. this.body.applyImpulse(impulse, point)
  40. }
  41. update() {
  42. this.body.quaternion.setFromAxisAngle(new CANNON.Vec3(0,0,1), this.angle)
  43. }
  44. worldEdgeWrap(worldBounds) {
  45. if(this.body.position.x >= worldBounds.width) {
  46. this.body.position.x -= worldBounds.width
  47. }
  48. if(this.body.position.x < 0) {
  49. this.body.position.x += worldBounds.width
  50. }
  51. if(this.body.position.y >= worldBounds.height) {
  52. this.body.position.y -= worldBounds.height
  53. }
  54. if(this.body.position.y < 0) {
  55. this.body.position.y += worldBounds.height
  56. }
  57. }
  58. draw(ctx) {
  59. ctx.save()
  60. ctx.translate(this.body.position.x, this.body.position.y)
  61. ctx.rotate(this.angle)
  62. ctx.fillStyle = this.color
  63. ctx.strokeStyle = this.color
  64. ctx.beginPath()
  65. ctx.arc(0, 0, this.radius, 0, 2 * Math.PI)
  66. ctx.closePath()
  67. ctx.fill()
  68. ctx.stroke()
  69. ctx.strokeStyle = "yellow"
  70. ctx.lineWidth = 1
  71. ctx.beginPath()
  72. ctx.moveTo(0,0)
  73. ctx.lineTo(4, 0)
  74. ctx.stroke()
  75. ctx.restore()
  76. }
  77. }