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