Question

I run into a problem. I would appreciate any help.

I am trying to shoot from a player position to mouse click position. Code gives me no error and according to my logic, it should work, but it doesn't

It creates the bullet object, but thats all.

//Bullets
   function bullet(id, color, size, speed, x, y, eX, eY) {
          this.id = id;           
          this.color = color;
          this.size = size;
          this.x = x;
          this.y = y;
          this.eX = eX;
          this.eY = eY;
          this.velocityX;
          this.velocityY;
          this.speed = speed;
      }

      var bulletList = []; 

      function addBullet(color, bsize, bspeed, x, y, eX, eY) {
          bulletList[bulletId] = new bullet(bulletId, color, bsize, bspeed, x, y, eX, eY);
          bulletId += 1;
      }

      function updateBullet(bullet, player)
      {
          var dx = (bullet.eX - player.x);
          var dy = (bullet.eY - player.y);
          var mag = Math.sqrt(dx * dx + dy * dy);              
          bullet.velocityX = (dx / mag) * speed;
          bullet.velocityY = (dy / mag) * speed;
          bullet.x += bullet.velocityX;
          bullet.y += bullet.velocityY;
      }

      // Add event listener for `click` events.
      canvas.onmousedown = function(e) {
          addBullet("black", 10, 2, playerList[0].x, playerList[0].y, e.x, e.y);
      }  
    //draw bullets (taken from drawFrame function)
                  $.each(bulletList, function (index, bullet) {  
                     updateBullet(bullet, playerList[0]);
                     ctx.fillStyle = bullet.color;
                     ctx.fillRect(bullet.x, bullet.y, bullet.size, bullet.size);
                  });  
Was it helpful?

Solution

Since you're already using jQuery, change the line

canvas.onmousedown = function(e) {
    addBullet("black", 10, 2, playerList[0].x, playerList[0].y, e.x, e.y);
}  

to

$(canvas).mousedown(function (e) {
    addBullet("black", 10, 2, playerList[0].x, playerList[0].y, e.clientX, e.clientY);
});

and consider moving all these inputs into a param object.

Also: never define your program inside an 'if', instead cancel 'if not'!

Working version: http://jsfiddle.net/LyUmZ/4/

EDIT: if jsfiddle does not work you may have run into into your browsers/noscripts xss guard, use xss->unsafe reload (in firefox noscript) and it should work.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top