在Phaser + P2和原始P2中使身体以相同的速度移动

时间:2015-01-31 04:17:14

标签: phaser-framework

我有一个客户端 - 服务器游戏,它使用P2作为一些基本的物理内容。我想在客户端运行带有P2的Phaser,在服务器上运行原始P2。客户端将使用本地P2来预测服务器的结果。但是我很难让机体在phaser + p2和raw p2中以相同的速度移动。

以下是两个同时运行的演示。知道这里发生了什么吗?

http://jsfiddle.net/ovcrn6bd/2/

<script src='https://cdn.rawgit.com/photonstorm/phaser/master/build/phaser.js'></script>
<script src="https://cdn.rawgit.com/schteppe/p2.js/master/build/p2.js"></script>

<canvas width="600" height="100" id="myCanvas" style='border:solid 1px'></canvas>

<script>

// Init phaser with a circle sprite.

PhaserController = function() {
  var controller = this
  var game = this.game = new Phaser.Game(600, 100, Phaser.AUTO, '', {
    create: function() {
      var radius = 20
      var bmd = game.make.bitmapData(radius * 2, radius * 2)
      bmd.circle(radius, radius, radius, '#ffffff')
      var sprite = this.sprite = game.add.sprite(30, 30, bmd)
      sprite.anchor.setTo(.5, .5)
      game.physics.startSystem(Phaser.Physics.P2JS)
      game.physics.p2.enable(sprite, false, false)
      game.physics.p2.frameRate = 1/30
      sprite.body.setCircle(radius, 0, 0, 0)
      sprite.body.friction = 0
      game.physics.p2.friction = 0

      // Make the circle move at a constant speed.

      sprite.update = function() {
        console.log('sprite update')
        sprite.body.velocity.x = 1
        sprite.body.velocity.y = 0
      }
    }
  })
}


P2Controller = function() {

  // Create a p2 circle and prepare a canvas.

  this.world = new p2.World({gravity:[0,0]})
  var circleShape = new p2.Circle(20)
  var body = new p2.Body({ mass:1, position:[30, 30] })
  body.addShape(circleShape)
  this.world.addBody(body)

  var canvas, ctx, w, h;
  canvas = document.getElementById("myCanvas");
  ctx = canvas.getContext("2d");
  ctx.lineWidth = 1;

  // Animate the circle moving across the canvas.

  function animate() {
    requestAnimationFrame(animate);
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    ctx.beginPath();
    var x = body.position[0],
        y = body.position[1],
        radius = body.shapes[0].radius;
    ctx.arc(x, y, radius, 0, 2 * Math.PI);
    ctx.stroke();
  }
  animate();

  this.frame_rate = 1/30

  // Start stepping the cicle.

  var controller = this
  function step_world() {
    console.log('step p2')
    body.velocity = [1, 0]
    controller.world.step(controller.frame_rate)
    setTimeout(step_world, controller.frame_rate)
  }
  step_world()
}

new PhaserController()
new P2Controller()
</script>

2 个答案:

答案 0 :(得分:0)

您的P2Controller似乎比PhaserController更频繁地发射。不太清楚为什么会发生这种情况,但要解决问题,你只需要调整一行。

更改

game.physics.p2.frameRate = 1/30 至 game.physics.p2.frameRate = 10/103

答案 1 :(得分:0)

我通过与Phaser分开使用P2解决了这个问题。我手动将我的精灵定位在P2体的位置。