bullet.js 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. function Bullet(game, ownerId) {
  2. this.position = {x: 0, y: 0};
  3. this.velocity = {x: 0, y: 0};
  4. this.acceleration = {x: 0, y: 0};
  5. this.angleRadians = 0;
  6. this.fireRate = 5;
  7. this.lifetime = 100;
  8. this.timeToDie = 0;
  9. this.isDead = false;
  10. this.owner = ownerId;
  11. this.damage = 1;
  12. this.fire = function(startPosition, startVelocity, directionRadians) {
  13. this.position.x = startPosition.x + 8 * Math.cos(directionRadians);
  14. this.position.y = startPosition.y + 8 * Math.sin(directionRadians);
  15. this.velocity.x = startVelocity.x;
  16. this.velocity.y = startVelocity.y;
  17. this.angleRadians = directionRadians;
  18. this.velocity.x += this.fireRate * Math.cos(directionRadians);
  19. this.velocity.y += this.fireRate * Math.sin(directionRadians);
  20. this.timeToDie = this.lifetime;
  21. }
  22. this.update = function(delta) {
  23. this.timeToDie -= delta;
  24. if(this.timeToDie <= 0) {
  25. game.expireBullet(this);
  26. return;
  27. }
  28. //bullets affected by gravity
  29. /*this.acceleration.x = 0;
  30. this.acceleration.y = 0;
  31. var nearestSystem = game.getNearestSystem(game, this);
  32. nearestSystem.addGravity(this);
  33. for(var index in nearestSystem.planets) {
  34. var planet = nearestSystem.planets[index];
  35. planet.addGravity(this);
  36. }
  37. this.velocity.x += this.acceleration.x;
  38. this.velocity.y += this.acceleration.y; */
  39. this.position.x += this.velocity.x * delta;
  40. this.position.y += this.velocity.y * delta;
  41. }
  42. this.draw = function(context) {
  43. if(this.isDead) {
  44. return;
  45. }
  46. //bullet
  47. context.fillStyle = "#DDDDDD";
  48. context.beginPath();
  49. context.arc(this.position.x, this.position.y, 2, 0, 2 * Math.PI);
  50. context.fill();
  51. //missile
  52. /*
  53. context.strokeStyle = "#DDDDDD";
  54. context.beginPath();
  55. context.moveTo(truePos.x, truePos.y);
  56. context.lineTo(truePos.x + 15* Math.cos(this.angleRadians), truePos.y + 15* Math.sin(this.angleRadians));
  57. context.stroke();
  58. */
  59. }
  60. this.checkHit = function(ship) {
  61. var distance = Math.sqrt(Math.pow(ship.position.x - this.position.x, 2) + Math.pow(ship.position.y - this.position.y, 2));
  62. if(ship.id != ownerId && ship.width / 2 >= distance) {
  63. ship.takeDamage(this.damage, ownerId);
  64. this.isDead = true;
  65. }
  66. }
  67. };