Phaser bow and arrow game, trajectory

The most popular phaser framework is very helpful to create html5 and javascript games.

I have come up with a simple trajectory code for a bow and arrow game.


var game = new Phaser.Game(800, 600, Phaser.AUTO, 'phaser-example', {
  preload: preload,
  create: create,
  update: update
});

var bow, bag, arrow, angle;
var score=0;
var x;
var y;
var oldx, oldy;
var xVel;  // calculate this based on distance
var yVel;  // 
var g = 0.25;
var arrowCreated = false;
var shot = false;

function preload() {
  game.load.image('bag', bagURI);
  game.load.image('bow', bowURI);
  game.load.image('arrow', arrowURI);

}

function create() {
  game.world.setBounds(0, 0, 800, 600);
  bow = game.add.sprite(100, 250, 'bow');
  bow.anchor.setTo(0.5);
  
  bag = game.add.sprite(650,300,'bag');
  bag.anchor.setTo(0.5);
  
  
  arrow = game.add.sprite(bow.x, bow.y, 'arrow');
  arrow.anchor.setTo(0.5);
  arrow.scale.setTo(0.5);
  arrow.angle = bow.angle;
  x = oldx = arrow.x;
  y = oldy = arrow.y;
  //game.input.onDown.add(createArrow, this);
  game.input.onUp.add(shootArrow, this);
}

function update() {
  //console.log(shot);
  if (!shot) {
    angle = Math.atan2(game.input.mousePointer.x - bow.x, -(game.input.mousePointer.y - bow.y)) * (180 / Math.PI) - 180;
    bow.angle = arrow.angle = angle;
    
  } else {
    
    //console.log("x",x,"y",y,"xVel",xVel,"yVel",yVel,"oldx",oldx,"oldy",oldy);
    
    x += xVel;
    y += yVel;
    yVel += g;

    arrow.x = x;
    arrow.y = y;
    
    
    arrowAngle = Math.atan2(x-oldx, -(y-oldy)) * (180 / Math.PI);
    arrow.angle = arrowAngle;
    /* need to write new arrow code */
    
     oldx = x;
     oldy = y;
    
    
    if(arrow.y>600) {
      resetArrow();
    }
    
    
    var intersects = Phaser.Rectangle.intersection(arrow, bag);
    if(intersects.width>0) {
      //console.log(intersects.width);
      resetArrow();
      score=score+45;
      console.log(score);
    }
    
  }
}
function resetArrow() {
  shot = false;
  arrow.x=bow.x;
  arrow.y=bow.y;

  x=oldx=arrow.x;
  y=oldy=arrow.y;
}
function createArrow() {
  arrowCreated = true;
}

function shootArrow() {
  if(!shot) {
    shot = true;
    xVel = - (game.input.mousePointer.x-bow.x)/6;
    yVel = - (game.input.mousePointer.y-bow.y)/6;
  }
}

 

Advertisements