Jump to content

Bullet go on mouse position


eihks
 Share

Recommended Posts

Hello guys,

I'm trying to make a little game with pixi,

My character can shoot fireball, but i want to them they go on the mouse position (current cursor position) like the screen.

here my bullet code if you need it

//create fireball

       var fireball = new PIXI.Texture.fromImage("public/tileset/fireball1.png");
        var bullets = [];
        var bulletSpeed = 1;

        function shoot(x,y, mX, mY){ //mX and mY = mouseX mouseY
            var fb = new PIXI.Sprite(fireball);
            fb.x = x;
            fb.y = y;
            fb.goToX = mX;
            fb.goToY = mY;
            app.stage.addChild(fb);
            bullets.push(fb);
        }

        document.addEventListener("click", function(e){
            shoot(player.x,player.y,e.clientX, e.clientY);
            console.log(fireball);
        })

function animate(e){
            requestAnimationFrame(animate);

            for(var b=bullets.length-1;b>=0;b--){
                bullets[b].x += bulletSpeed;
                bullets[b].y -= bulletSpeed;
            }
        }
        animate();

I tried to make it but was not fonctionnal haha.

If someone have a idea for do it let me know please ! :)

Thanks  and sorry for my bad english ! 

 

1.png

Link to comment
Share on other sites

Calculate a vector from player to target, then normalize it and then on each render pass just add the vector amount multiplied by speed to bullets position.

Short pseudoexample:
 

var bulletSpeed = 5;
var bullets = [];

function shoot(){
  var direction = new Point();
  direction.x = target.x - player.x;
  direction.y = target.y - player.y);

  //Normalize
  var length = Math.sqrt( direction.x*direction.x + direction.y*direction.y);
  direction.x/=length;
  direction.y/=length;

  var bullet = new Sprite();
  bullet.direction = direction;
  bullets.push(bulllet);
  app.stage.addChild(bullet);
}


function animate(){
  for( var i = 0; i < bullets.length; i++){
    bullet.x += bullet.direction.x*bulletSpeed;
    bullet.y += bullet.direction.y*bulletSpeed;
    //Hit detection here
  }
}


I can make a proper example at some point if needed.

Link to comment
Share on other sites

  • 2 years later...

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...