2015-05-25 2 views
0

Я делаю прокруткой с использованием Phaser (последняя версия), и я хочу, чтобы снаряды игрока двигались к указателю, когда игрок щелкает, как в этом примере http://phaser.io/examples/v2/games/tanks. Я использовал некоторый код из примера, но в моей игре координаты activePointer x и y кажутся инициализированными только тогда, когда игра начинается и никогда не изменяется. Поэтому, когда игрок стреляет, он всегда идет к тем же координатам.Местоположение ActivePointer не обновляется

У меня есть следующий код (обратите внимание, я удалил биты о коллекции элементов, врагов и т.д. для размещения здесь):

var SideScroller = SideScroller || {}; 

var startPosX = 100; 
var startPosY = 300; 

var shooter; 

var playerBullets; 
var nextFire = 0; 
var fireRate = 100; 
var cursors; 
var currentLoc; 

SideScroller.Game = function() {}; 

SideScroller.Game.prototype = { 

    create: function() { 

     //create player 
     //params = (game, startPositionX,startPositionY, key, frame) 
     this.player = this.game.add.sprite(startPosX, startPosY, 'player'); 

     //get canvas width and height for later use 
     canvasWidth = this.game.canvas.width; 
     canvasHeight = this.game.canvas.height; 

     //create enemy 
     var x = this.game.rnd.between(80, this.game.world.width); 
     var y = this.game.rnd.between(0, 113); 

     // Point to shoot projectiles from 
     // allows rotation, if this had been done on the player object, the graphic would have rotated, which we don't want 
     this.shooter = this.game.add.sprite(startPosX, startPosY, 'blank'); 
     this.shooter.anchor.setTo(0.5, 0.5); 

     //make a group of player projectiles 
     playerBullets = this.game.add.group(); 
     playerBullets.enableBody = true; 
     playerBullets.physicsBodyType = Phaser.Physics.ARCADE; 
     playerBullets.createMultiple(1000, 'peePower'); 

     playerBullets.setAll('anchor.x', 0.5); 
     playerBullets.setAll('anchor.y', 0.5); 
     playerBullets.setAll('outOfBoundsKill', true); 
     playerBullets.setAll('checkWorldBounds', true); 

     //enable physics on the player 
     this.game.physics.arcade.enable(this.player); 

     //bring player shooting point to the top (not totally necessary) 
     this.shooter.bringToTop(); 

     //player gravity 
     this.player.body.gravity.y = gravity; 

     //player collides with all four edges of the game world 
     this.player.body.collideWorldBounds = true; 

     this.player.anchor.setTo(0.5, 0.5); 

     //the camera will follow the player in the world 
     this.game.camera.follow(this.player); 

     //move player with cursor keys 
     cursors = this.game.input.keyboard.createCursorKeys(); 
    }, 

    update: function() { 
     currentLoc = this.game.input.activePointer; 
     //collision between player and platforms 
     this.game.physics.arcade.collide(this.player, this.blockedLayer, null, null, this); 

     //make co-ordinates match 
     this.shooter.x = this.player.x; 
     this.shooter.y = this.player.y; 

     //this.shooter's angle towards 
     this.shooter.rotation = this.game.physics.arcade.angleToPointer(this.shooter, this.game.input.activePointer); 

     //only respond to keys if the player is alive 
     if (this.player.alive) { 
      this.player.body.velocity.x = 0; 

      if (this.game.input.activePointer.isDown) { 
       console.log("pointer is down"); 
       this.fire(); 
      } 
      else if (cursors.right.isDown) { 
       this.playerForward(); 
      } 
      else if (cursors.left.isDown) { 
       this.playerBack(); 
      } 
      else if (cursors.up.isDown) { 
       this.playerJump(); 
      } 
      else if (cursors.down.isDown) { 
       this.fire(); 
       this.playerDuck(); 
      }    
     } 
    }, 

    fire: function() {  
     //for debugging 
     console.log("fire was called"); 
     console.log(this.game.input.activePointer.x); 
     console.log(this.game.input.activePointer.y); 

     if (this.game.time.now > nextFire && playerBullets.countDead() > 0) 
     { 
      nextFire = this.game.time.now + fireRate; 
      var bullet = playerBullets.getFirstExists(false); 
      bullet.reset(this.shooter.x, this.shooter.y); 

      currentLoc = this.game.input.activePointer; 
      bullet.rotation = this.game.physics.arcade.moveToPointer(bullet, 1000, currentLoc, 1000); 

      console.log(this.game.input.activePointer); 
     } 

    }, 
    playerForward: function() { 
     this.player.loadTexture('player'); 
     this.player.body.setSize(this.player.standDimensions.width, this.player.standDimensions.height); 
     this.player.body.velocity.x = 700; 
     this.player.isMoving = true; 
     //console.log("Forward height:" + this.player.standDimensions.height); 
     //console.log("Forward width:" + this.player.standDimensions.width); 
    }, 

    playerBack: function() { 
     this.player.loadTexture('playerBack'); 
     this.player.body.velocity.x -= 700; 
     this.player.isMoving = true; 
    }, 

    playerJump: function() { 
     if (this.player.body.blocked.down) { 
      this.player.body.velocity.y -= 700; 
      this.player.loadTexture('playerJump'); 
      //console.log("Jump height:" + this.player.jumpDimensions.height); 
      //console.log("Jump width:" + this.player.jumpDimensions.width);  
     } 
    }, 

    playerDuck: function() { 
     //change image and update the body size for the physics engine 
     this.player.loadTexture('playerDuck'); 
     this.player.body.setSize(this.player.duckedDimensions.width, this.player.duckedDimensions.height); 

     //keep track of whether player is ducked or not 
     this.player.isDucked = true; 
    }, 

    playerDead: function() { 
     //set to dead (this doesn't affect rendering) 
     this.player.alive = false; 

     //stop moving to the right 
     this.player.body.velocity.x = 0; 

     //change sprite image 
     this.player.loadTexture('playerDead'); 

    }, 

}; 

Shooter является пустой спрайт на верхней части плеера (подобно башне в примере резервуара), чтобы разрешить вращение без поворота игрока (сообщите мне также, если есть лучший способ сделать это!).

Я попробовал обновить переменную currentLoc в методе обновления до места activePointer, но это не сработало.

Кроме того, это условие никогда не был поражен:

if (this.game.input.activePointer.isDown) { 
    console.log("pointer is down"); 
    this.fire(); 
} 

Так что что-то должно идти наперекосяк с обнаружением щелчков мышью, и я не знаю, если это часть проблемы?

ответ

0

Я думаю, вы должны посмотреть его в API. В вашем коде есть несколько моментов, которые сомнительны. http://phaser.io/docs/2.3.0/Phaser.Pointer.html http://phaser.io/docs/2.3.0/Phaser.Physics.Arcade.html#moveToPointer

Дело в том, что вы на самом деле дает ссылку на указатель (для currentLoc), но не позицию. Поэтому он должен всегда стрелять 0; 0.

И для обнаружения isDown, вы сделали это в функции обновления или где-то еще?

Надеюсь, что смогу помочь!

Смежные вопросы