Phaser3 - 在 Physics arcade 引擎上为车辆添加加速和阻力

Phaser3 - Add acceleration and drag to vehicle on Physics arcade engine

我正在 Phaser3 中制作一个简单的自上而下的汽车游戏。此刻,我的车在匀速行驶。

但是,我希望它表现得更真实,应用 drag/friction/acceleration 等元素,有点像 http://domasx2.github.io/gamejs-box2d-car-example/ 中的示例。

如何使用 Phaser Physics 街机引擎(我的游戏的其余部分目前使用的引擎)让它以这种方式运行。

我的代码如下:

import Phaser from "phaser";

const config = {
  type: Phaser.AUTO,
  parent: "phaser-example",
  width: 800,
  height: 600,
  physics: {
    default: "arcade",
    arcade: {
      debug: true
    }
  },
  scene: {
    preload: preload,
    create: create,
    update: update,
    render: render
  }
};

const game = new Phaser.Game(config);
let platform;
let player;
let cursors;

function preload() {
  this.load.image("car", "https://labs.phaser.io/assets/sprites/car90.png");
  this.load.image("sky", "https://labs.phaser.io/assets/skies/gradient11.png");
}

function create() {
  this.add.image(400, 300, "sky");

  player = this.physics.add.sprite(400, 300, "car", 1);
  player.body.setBounce(20, 20);
  player.setCollideWorldBounds(true);

  cursors = this.input.keyboard.createCursorKeys();

  this.physics.add.collider(player, platform);
}

function update() {
  player.body.velocity.x = 0;
  player.body.velocity.y = 0;
  player.body.angularVelocity = 0;

  if (cursors.left.isDown) {
    player.body.angularVelocity = -150;
  }
  if (cursors.right.isDown) {
    player.body.angularVelocity = 150;
  }

  if (cursors.up.isDown) {
    this.physics.velocityFromRotation(
      player.rotation,
      150,
      player.body.velocity
    );
  }
  if (cursors.down.isDown) {
    this.physics.velocityFromRotation(
      player.rotation,
      -150,
      player.body.velocity
    );
  }
}

function render() {}

此处为 Stackblitz 演示:https://stackblitz.com/edit/phaser3-typescript-d6zbzf

对于拖动,您可以将此语句添加到您的 create() 函数中:

player.setDrag(0.90);

针对恒定速度,您可以将 update() 部分更改为:

  if (cursors.up.isDown) {
    // Go faster
    player.body.acceleration.setToPolar(player.rotation, 100);
  }
  if (cursors.down.isDown) {
    // Brake
    let speed = player.body.velocity.length();
    player.body.acceleration.setToPolar(player.rotation - Math.PI, 2 * speed);
    if (speed < 3) {
      // Come to a full stop
      player.body.setVelocity(0);
    }
  }

这不是设置速度,而是将前向加速度设置为固定数值。上面的代码不允许玩家倒退。这可能不是你想要的。

如果速度低于特定数值,例如,您也可以阻止转弯。 3.