简体   繁体   中英

Phaser 3 - bounce back sprite on collision with object

In Phaser3, how do you make a sprite bounce back when it collides with an object? At the moment, I can detect a collision, but I want the car to bounce back when it collides.

My code:

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');
  this.load.image('ground', 'https://labs.phaser.io/assets/sprites/platform.png');
}

function create() {
  this.add.image(400, 300, 'sky');
  
  platform = this.physics.add.image(400, 400, 'ground');
  platform.body.setBounce(20, 20);
  platform.setImmovable(true);

  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 = -40;
  }
  if (cursors.right.isDown) {
    player.body.angularVelocity = 40;
  }

  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-ctun9e

Firstly, your velocity is being reset to 0 every frame, and reset to a static value depending on the keyboard input. Bounce is an event that alters an object's body's velocity, so resetting this velocity every update frame will make it look like set bounce isn't working.

Secondly, set bounce expects a float between 0 and 1, it looks like you can set it higher for a collision that reflects faster than the incoming speed, but 20 is far too high, once it collides with a value higher than 1, the sprite starts colliding with all the world bounds at ever-increasing speeds.

Linked a fork of your stackblitz with the set bounce at 1 and removing the reset of velocity when keys are not pressed. Stackblitz

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM