component.js 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. function component(width, height, color, x, y, type) {
  2. this.type = type;
  3. this.score = 0;
  4. this.width = width;
  5. this.height = height;
  6. this.speedX = 0;
  7. this.speedY = 0;
  8. this.x = x;
  9. this.y = y;
  10. this.gravity = 0;
  11. this.gravitySpeed = 0;
  12. this.isMoving = false;
  13. this.direction = true;
  14. this.isJumping = false;
  15. if (type == "image") {
  16. this.image = new Image();
  17. this.image.src = color;
  18. }
  19. this.update = function() {
  20. ctx = myGameArea.context;
  21. if (type == "image") {
  22. if(this.direction){
  23. ctx.drawImage(this.image,
  24. this.x,
  25. this.y,
  26. this.width, this.height);
  27. }else{
  28. ctx.drawImage(this.image,
  29. this.x+this.width,
  30. this.y,
  31. this.width, this.height);
  32. }
  33. } else {
  34. ctx.fillStyle = color;
  35. ctx.fillRect(this.x, this.y, this.width, this.height);
  36. }
  37. }
  38. this.newPos = function() {
  39. this.gravitySpeed += this.gravity;
  40. this.x += this.speedX;
  41. this.y += this.speedY + this.gravitySpeed;
  42. this.hitBottom();
  43. if(!myGamePiece.isMoving){
  44. myGamePiece.image.src = charAnim[0];
  45. }
  46. }
  47. this.hitBottom = function() {
  48. var rockbottom = myGameArea.canvas.height - this.height;
  49. if (this.y > rockbottom) {
  50. this.y = rockbottom;
  51. this.gravitySpeed = 0;
  52. this.isJumping = false;
  53. }else{
  54. this.isJumping = true;
  55. }
  56. }
  57. this.crashWith = function(otherobj) {
  58. var myleft = this.x;
  59. var myright = this.x + (this.width);
  60. var mytop = this.y;
  61. var mybottom = this.y + (this.height);
  62. var otherleft = otherobj.x;
  63. var otherright = otherobj.x + (otherobj.width);
  64. var othertop = otherobj.y;
  65. var otherbottom = otherobj.y + (otherobj.height);
  66. var crash = true;
  67. if ((mybottom < othertop) || (mytop > otherbottom) || (myright < otherleft) || (myleft > otherright)) {
  68. crash = false;
  69. }
  70. return crash;
  71. }
  72. this.moveRight = function(n) {
  73. myGamePiece.speedX = n;
  74. myGamePiece.isMoving = true;
  75. myGamePiece.direction = true;
  76. }
  77. this.moveLeft = function(n){
  78. myGamePiece.speedX = -n;
  79. myGamePiece.isMoving = true;
  80. myGamePiece.direction = false;
  81. }
  82. this.jump = function(n){
  83. //myGamePiece.isJumping = true;
  84. myGamePiece.speedY = -n;
  85. //myGamePiece.y = myGameArea.canvas.height - n;
  86. myGamePiece.isMoving = true;
  87. //console.log("salto");
  88. }
  89. }