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
Related
I am having problem trying to make a spinning wheel spin automatically on page load and also display multiple wheels on the same page. The spinner is based on Phaser. I am not a JavaScript nor Phaser programmer so your assistance is appreciated. This is probably something simple to do.
Here is the game.js code for the spinning wheel. (The complete spinning wheel script can be downloaded here)
// the game itself
var game;
var gameOptions = {
// slices (prizes) placed in the wheel
slices: 8,
// prize names, starting from 12 o'clock going clockwise
slicePrizes: ["A KEY!!!", "50 STARS", "500 STARS", "BAD LUCK!!!", "200 STARS", "100 STARS", "150 STARS", "BAD LUCK!!!"],
// wheel rotation duration, in milliseconds
rotationTime: 3000
}
// once the window loads...
window.onload = function() {
// game configuration object
var gameConfig = {
// render type
type: Phaser.CANVAS,
// game width, in pixels
width: 550,
// game height, in pixels
height: 550,
// game background color
backgroundColor: 0x880044,
// scenes used by the game
scene: [playGame]
};
// game constructor
game = new Phaser.Game(gameConfig);
// pure javascript to give focus to the page/frame and scale the game
window.focus()
resize();
window.addEventListener("resize", resize, false);
}
// PlayGame scene
class playGame extends Phaser.Scene{
// constructor
constructor(){
super("PlayGame");
}
// method to be executed when the scene preloads
preload(){
// loading assets
this.load.image("wheel", "wheel.png");
this.load.image("pin", "pin.png");
}
// method to be executed once the scene has been created
create(){
// adding the wheel in the middle of the canvas
this.wheel = this.add.sprite(game.config.width / 2, game.config.height / 2, "wheel");
// adding the pin in the middle of the canvas
this.pin = this.add.sprite(game.config.width / 2, game.config.height / 2, "pin");
// adding the text field
this.prizeText = this.add.text(game.config.width / 2, game.config.height - 20, "Spin the wheel", {
font: "bold 32px Arial",
align: "center",
color: "white"
});
// center the text
this.prizeText.setOrigin(0.5);
// the game has just started = we can spin the wheel
this.canSpin = true;
// waiting for your input, then calling "spinWheel" function
this.input.on("pointerdown", this.spinWheel, this);
}
// function to spin the wheel
spinWheel(){
// can we spin the wheel?
if(this.canSpin){
// resetting text field
this.prizeText.setText("");
// the wheel will spin round from 2 to 4 times. This is just coreography
var rounds = Phaser.Math.Between(2, 4);
// then will rotate by a random number from 0 to 360 degrees. This is the actual spin
var degrees = Phaser.Math.Between(0, 360);
// before the wheel ends spinning, we already know the prize according to "degrees" rotation and the number of slices
var prize = gameOptions.slices - 1 - Math.floor(degrees / (360 / gameOptions.slices));
// now the wheel cannot spin because it's already spinning
this.canSpin = false;
// animation tweeen for the spin: duration 3s, will rotate by (360 * rounds + degrees) degrees
// the quadratic easing will simulate friction
this.tweens.add({
// adding the wheel to tween targets
targets: [this.wheel],
// angle destination
angle: 360 * rounds + degrees,
// tween duration
duration: gameOptions.rotationTime,
// tween easing
ease: "Cubic.easeOut",
// callback scope
callbackScope: this,
// function to be executed once the tween has been completed
onComplete: function(tween){
// displaying prize text
this.prizeText.setText(gameOptions.slicePrizes[prize]);
// player can spin again
this.canSpin = true;
}
});
}
}
}
// pure javascript to scale the game
function resize() {
var canvas = document.querySelector("canvas");
var windowWidth = window.innerWidth;
var windowHeight = window.innerHeight;
var windowRatio = windowWidth / windowHeight;
var gameRatio = game.config.width / game.config.height;
if(windowRatio < gameRatio){
canvas.style.width = windowWidth + "px";
canvas.style.height = (windowWidth / gameRatio) + "px";
}
else{
canvas.style.width = (windowHeight * gameRatio) + "px";
canvas.style.height = windowHeight + "px";
}
}
Does anyone know how to make it so that
it will start spinning as soon as the page is loaded.
place more than one wheel on a page. When I call the JavaScript twice, it does not display two wheels. The purpose of this exercise is to feed the wheel with two different "degrees" so that it can display the two results. The alternative will be to spin the wheel twice. After the first spin, display the first result and spin again to display the second result. But this is probably harder to do than simply display two wheels.
Thanks in advance.
For the first part of your question , '...spinning as soon as page is loaded..', the answer is:
just add the code line this.spinWheel(); at the end of the create function, this will start it right away.
For the second part:
just add in the gameConfig - object the property parent, with an id of an html-tag
create a game instance (no action needed)
than copy and past the whole gameConfig
change the parent, to a different tag-id
create a second game instance. ( add the line game = new Phaser.Game(gameConfig);)
Here a short Demo showcasing, these two fixes:
(depending on your exact goal, and what you want to achieve, there might be better ways to solve this)
FYI:
Images are not loaded, because they won't work here, but one can see how the auto spinning would work.
I remove code that was not so relevant for the demo, so that it can be understund more easy.
document.body.style = 'margin:0;';
var gameOptions = {
slices: 8,
slicePrizes: ["A KEY!!!", "50 STARS", "500 STARS", "BAD LUCK!!!", "200 STARS", "100 STARS", "150 STARS", "BAD LUCK!!!"],
rotationTime: 3000
}
class playGame extends Phaser.Scene{
constructor(){
super("PlayGame");
}
preload(){
//this.load.image("wheel", "wheel.png");
//this.load.image("pin", "pin.png");
}
create(){
this.wheel = this.add.sprite(game.config.width / 2, game.config.height / 2, "wheel");
this.pin = this.add.sprite(game.config.width / 2, game.config.height / 2, "pin");
this.prizeText = this.add.text(game.config.width / 2, game.config.height - 20, "Spin the wheel", {
font: "bold 32px Arial",
align: "center",
color: "white"
});
this.prizeText.setOrigin(0.5);
this.canSpin = true;
this.input.on("pointerdown", this.spinWheel, this);
this.spinWheel();
}
spinWheel(){
if(this.canSpin){
this.prizeText.setText("");
var rounds = Phaser.Math.Between(2, 4);
var degrees = Phaser.Math.Between(0, 360);
var prize = gameOptions.slices - 1 - Math.floor(degrees / (360 / gameOptions.slices));
this.canSpin = false;
this.tweens.add({
targets: [this.wheel],
angle: 360 * rounds + degrees,
duration: gameOptions.rotationTime,
ease: "Cubic.easeOut",
callbackScope: this,
onComplete: function(tween){
this.prizeText.setText(gameOptions.slicePrizes[prize]);
this.canSpin = true;
}
});
}
}
}
var gameConfig = {
type: Phaser.CANVAS,
parent: 'wheel1',
width: 200,
height: 200,
backgroundColor: 0x880044,
scene: [playGame]
};
var game = new Phaser.Game(gameConfig);
gameConfig = {
type: Phaser.CANVAS,
parent: 'wheel2',
width: 200,
height: 200,
// I altered also the background color to show the difference
backgroundColor: 0x0ff044,
scene: [playGame]
};
game = new Phaser.Game(gameConfig);
#wheel1, #wheel2, canvas{
display:inline-block;
padding:0;
margin:0;
}
<script src="https://cdn.jsdelivr.net/npm/phaser#3.55.2/dist/phaser.js"></script>
<div id="wheel1"></div><div id="wheel2"></div>
Updated - Update:
The main problem is that I made a mistake, the property is not parentElement it is parent. I tried to fix this in following demo.
// the game itself
var game;
var gameOptions = {
// slices (prizes) placed in the wheel
slices: 8,
// prize names, starting from 12 o'clock going clockwise
// this array has to contain atleast 8 value
slicePrizes: ["A KEY!!!", "50 STARS", "500 STARS", "BAD LUCK!!!", "200 STARS", "100 STARS", "150 STARS", "BAD LUCK!!!"],
// wheel rotation duration, in milliseconds
rotationTime: 3000
}
var gameConfig;
// once the window loads...
window.onload = function () {
gameConfig = {
type: Phaser.CANVAS,
parent: 'wheel1',
width: 200,
height: 200,
backgroundColor: 0x880044,
scene: [playGame]
};
var game = new Phaser.Game(gameConfig);
game.scene.start('PlayGame', { degrees: 60 });
gameConfig = {
type: Phaser.CANVAS,
parent: 'wheel2',
width: 200,
height: 200,
// I altered also the background color to show the difference
backgroundColor: 0x0ff044,
scene: [playGame]
};
var game2 = new Phaser.Game(gameConfig);
game2.scene.start('PlayGame', { degrees: 40 });
window.focus()
resize();
window.addEventListener("resize", resize, false);
}
// PlayGame scene
class playGame extends Phaser.Scene {
// constructor
constructor() {
super({ key: "PlayGame" });
}
// method to be executed when the scene preloads
preload() {
// loading assets
//this.load.image("wheel", "wheel.png");
//this.load.image("pin", "pin.png");
}
// method to be executed once the scene has been created
create(data) {
// adding the wheel in the middle of the canvas
this.wheel = this.add.sprite(gameConfig.width / 2, gameConfig.height / 2, "wheel");
// adding the pin in the middle of the canvas
this.pin = this.add.sprite(gameConfig.width / 2, gameConfig.height / 2, "pin");
// adding the text field
this.prizeText = this.add.text(gameConfig.width / 2, gameConfig.height - 20, "Spin the wheel", {
font: "bold 32px Arial",
align: "center",
color: "black"
});
// center the text
this.prizeText.setOrigin(0.5);
// the game has just started = we can spin the wheel
this.canSpin = true;
//this.input.on("pointerdown", this.spinWheel, this);
this.spinWheel(data.degrees);
}
// function to spin the wheel
spinWheel(degrees) {
// can we spin the wheel?
if (this.canSpin) {
// resetting text field
this.prizeText.setText("");
// the wheel will spin round from 2 to 4 times. This is just coreography
var rounds = Phaser.Math.Between(8, 10);
//var degrees = Phaser.Math.Between(0, 360);
var prize = gameOptions.slices - 1 - Math.floor(degrees / (360 / gameOptions.slices));
// now the wheel cannot spin because it's already spinning
this.canSpin = false;
// animation tweeen for the spin: duration 3s, will rotate by (360 * rounds + degrees) degrees
// the quadratic easing will simulate friction
this.tweens.add({
// adding the wheel to tween targets
targets: [this.wheel],
// angle destination
angle: 360 * rounds + degrees,
// tween duration
duration: gameOptions.rotationTime,
// tween easing
ease: "Cubic.easeOut",
// callback scope
callbackScope: this,
// function to be executed once the tween has been completed
onComplete: function (tween) {
// displaying prize text
this.prizeText.setText(gameOptions.slicePrizes[prize]);
// player can spin again
this.canSpin = true;
}
});
}
}
}
// pure javascript to scale the game
function resize() {
var canvas = document.querySelector("#wheels");
var windowWidth = window.innerWidth;
var windowHeight = window.innerHeight;
var windowRatio = windowWidth / windowHeight;
var gameRatio = gameConfig.width / gameConfig.height;
if (windowRatio < gameRatio) {
canvas.style.width = windowWidth + "px";
//canvas.style.height = (windowWidth / gameRatio) + "px";
}
else {
canvas.style.width = (windowHeight * gameRatio) + "px";
//canvas.style.height = windowHeight + "px";
}
}
body{
padding: 0px;
margin: 0px;
}
#wheels{
display: flex;
margin: 0;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
align-items: stretch;
}
#wheel1, #wheel2, canvas{
flex-grow: 1;
margin: 0;
padding: 0;
}
canvas{
width: 100%;
}
<script src="https://cdn.jsdelivr.net/npm/phaser#3.55.2/dist/phaser.js"></script>
<div id="wheels">
<div id="wheel1"></div>
<div id="wheel2"></div>
</div>
I am developing an arcade game in Phaser 3, the problem is that the player sprite is dropped from the top of the screen when the game loads and I don't want that, I want him to be rendered without falling so I set the y gravity to 0 in order to achieve that. That works, however now my player cannot jump, I am trying to reset the gravity to 300 on keyDown but that isn't working, how can I achieve that? I tried to set the y gravity to 300 again in the create function but that didn't work too is it possible?
Here is my code:
// let gravity = 0
let config = {
type: Phaser.AUTO,
width: 800,
height: 500,
physics: {
default: 'arcade',
arcade: {
gravity: { y: 0 },
debug: false
}
},
scene: {
preload: preload,
create: create,
update: update
},
scale: {
mode: Phaser.Scale.FIT,
parent: 'root',
autoCenter: Phaser.Scale.CENTER_BOTH,
width: 800,
height: 600
},
};
new Phaser.Game(config)
function preload() {
this.load.image('sky', require('../assets/backgrounds/sky.png'));
this.load.image('jungle', require('../assets/backgrounds/jungle.png'));
this.load.image('ground', require('../assets/tiles/ground-transp.png'))
this.load.image('small-platform', require("../assets/tiles/small-platform-removebg-preview.png"))
this.load.image('jungle-platform', require("../assets/tiles/jungle-platform.png"))
this.load.image('large-platform', require("../assets/tiles/large-platform-removebg-preview.png"))
this.load.image('tree', require("../assets/backgrounds/treetrunk.png"))
this.load.image('plant', require("../assets/backgrounds/plant.png"))
this.load.image('plant2', require("../assets/backgrounds/plants2.png"))
this.load.image('rock', require("../assets/backgrounds/rock.png"))
this.load.atlas('sacred', require('../assets/spritesheets/sacredRock.png'), require('../assets/spritesheets/sacredRock.json'))
this.load.atlas('player', require('../assets/spritesheets/dilopodon.png'), require('../assets/spritesheets/dilopodon.json'))
this.load.tilemapTiledJSON('Ground', require('../assets/maps/simple-tutorial.json'));
}
function create () {
this.bg = this.add.image(-41, -41, 'sky');
this.bg = this.add.image('jungle');
this.add.image(67, 370, 'tree')
this.add.image(167, 429, 'plant')
this.add.image(700, 405, 'plant2')
this.add.image(300, 440, 'rock')
const map = this.make.tilemap({ key: 'Ground' })
// Creating tilesets
const groundTileSet = map.addTilesetImage('Ground', 'ground')
const platformTileset = map.addTilesetImage('small-platform', 'small-platform')
const junglePlatformTileset = map.addTilesetImage('jungle-platform', 'jungle-platform')
const largePlatformTileset = map.addTilesetImage('large-platform', 'large-platform')
let groundLayer = map.createLayer('Ground', [groundTileSet, platformTileset, junglePlatformTileset, largePlatformTileset])
groundLayer.setCollisionByExclusion([-1]);
// Creating the Player
player = this.physics.add.sprite(100, 420, 'player')
player.setBounce(0.2);
player.setCollideWorldBounds(true)
player.body.width = 60
player.body.height = 60
player.body.offset.x = 10
player.body.offset.x = 10
// Creating the Sacred Stone
sacredStone = this.physics.add.sprite(400, 270, 'sacred')
sacredStone.setCollideWorldBounds(true)
sacredStone.body.width = 60
sacredStone.body.height = 230
//Physics
this.physics.add.collider(groundLayer, player )
this.physics.add.collider(groundLayer, sacredStone )
// Debug graphics
// let graphics = this.add.graphics()
// groundLayer.renderDebug(graphics, {
// tileColor: new Phaser.Display.Color(0, 0, 255, 50), // Non-colliding tiles
// collidingTileColor: new Phaser.Display.Color(0, 255, 0, 100), // Colliding tiles
// faceColor: new Phaser.Display.Color(255, 0, 0, 100) // Colliding face edges
// });
// let frameNames = this.textures.get('player').getFrameNames();
function update() {
sacredStone.anims.play('glow', true)
if (cursors.left.isDown)
{
player.setVelocityX(-160);
player.anims.play('walkLeft', true);
}
else if (cursors.right.isDown)
{
player.setVelocityX(160);
player.anims.play('walkRight', true)
}
else
{
player.setVelocityX(0);
player.anims.play('idle', true);
}
if (cursors.up.isDown && player.body.blocked.down)
{
config.physics.arcade.gravity.y = 300
player.setVelocityY(-330);
}
}
I think the problem is, that when you set the position of the player in the game, you are setting it to low. When two gameObject within arcade physics overlap, they can't collide anymore, so they fall through.
I would set the gravity again, and than just set the position of the player just a few pixels higher -10 might be enough. If it still falls through set it higher until it works. I think the sacredStone has the same issue.
I've created a slingshot game in matter.js where I've created a ball which is used as a sling and some target balls on a ground which should be pushed off. I've attached the code below. I need help in tracking score so that everytime time user pushes all the balls off the ground "You won!" message should be displayed. Also need help in adding reset button. Link to the live game
let engine = Matter.Engine.create();
let render = Matter.Render.create({
element: document.body,
engine: engine,
options: {
width: 1600,
height: 800,
wireframes: false
}
});
let ground = Matter.Bodies.rectangle(1200, 500, 300, 60, { isStatic: true });
let mouse = Matter.Mouse.create(render.canvas);
let mouseConstraint = Matter.MouseConstraint.create(engine, {
mouse: mouse,
constraint: {
render: {visible: false}
}
});
render.mouse = mouse;
let ball = Matter.Bodies.circle(300, 600, 20);
let sling = Matter.Constraint.create({
pointA: {x:300, y:600},
bodyB: ball,
stiffness: 0.05
})
let stack = Matter.Composites.stack(1100, 270, 4, 4, 0, 0, function(x, y){
return Matter.Bodies.polygon(x, y, 8, 30);
});
let firing = false;
Matter.Events.on(mouseConstraint, 'enddrag', function(e){
if(e.body === ball) firing = true;
});
Matter.Events.on(engine, 'afterUpdate', function(){
if(firing && Math.abs(ball.position.x-300)<200 && Math.abs(ball.position.y-600)<20){
ball = Matter.Bodies.circle(300, 600, 20);
Matter.World.add(engine.world, ball);
sling.bodyB = ball;
firing = false;
}
})
Matter.World.add(engine.world, [stack, ground,ball, sling, mouseConstraint]);
Matter.Engine.run(engine);
Matter.Render.run(render);
I am trying to port the following Phaser2 example (https://phaser.io/examples/v2/tilemaps/fill-tiles) into Phaser3. I am experiencing two issues:
I cannot rotate the vehicle as the left/right keys will not work.
I cannot get the tilemap to display correctly, it seems cut off.
import Phaser from "phaser";
const config = {
type: Phaser.AUTO,
parent: "phaser-example",
width: 800,
height: 600,
physics: {
default: 'arcade'
},
scene: {
preload: preload,
create: create,
update: update,
render: render
}
};
const game = new Phaser.Game(config);
let cursors;
let player;
let map;
let speed = 0;
function preload() {
this.load.tilemapTiledJSON('desert', 'desert.json');
this.load.image('tiles', 'https://examples.phaser.io/assets/tilemaps/tiles/tmw_desert_spacing.png')
this.load.image('car', 'http://labs.phaser.io/assets/sprites/car90.png')
}
function create() {
map = this.make.tilemap({ key: 'desert' });
const tiles = map.addTilesetImage('Desert', 'tiles');
const layer = map.createDynamicLayer('Ground', tiles, 0, 0);
cursors = this.input.keyboard.createCursorKeys();
player = this.physics.add.sprite(450, 80, 'car');
this.cameras.main.startFollow(player, true, 0.05, 0.05);
}
function update() {
// Drive forward if cursor up key is pressed down
if (cursors.up.isDown && speed <= 400) {
speed += 10;
} else {
if (speed >= 10) {
speed -= 10
}
}
// Drive backwards if cursor down key is pressed down
if (cursors.down.isDown && speed >= -200) {
speed -= 5;
} else {
if (speed <= -5) {
speed += 5
}
}
// Steer the car
if (cursors.left.isDown) {
player.body.angularVelocity = -5 * (speed / 1000);
} else if (cursors.right.isDown) {
player.body.angularVelocity = 5 * (speed / 1000);
} else {
player.body.angularVelocity = 0;
}
player.body.velocity.x = speed * Math.cos((player.body.angle - 360) * 0.01745);
player.body.velocity.y = speed * Math.sin((player.body.angle - 360) * 0.01745);
}
function render() {
}
How can I fix this?
I loaded the code in a blank project without assets, and was able to see the image missing object rotate. However, it looks like the dependency of speed in angular rotation is too low. If you reduce the decrease in scaling of speed used for calculating angular velocity, you can get the car to turn more quickly.
Proof -> https://stackblitz.com/edit/phaser-2-example-so
Here is such a code snippet:
var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { preload: preload, create: create });
var emitter;
function preload() {
game.load.image('wasp', 'assets/glass.png');
game.load.image('glass', 'assets/glass.png');
game.load.image('water', 'assets/blue-raster-floor.png');
}
function create() {
game.physics.startSystem(Phaser.Physics.ARCADE);
game.add.tileSprite(0, 344, 800, 256, 'water');
emitter = game.add.emitter(game.world.centerX, 200);
emitter.makeParticles('glass');
emitter.setXSpeed(-200, 200);
emitter.setYSpeed(-150, -250);
emitter.bringToTop = true;
emitter.setAlpha(0.1, 1, 500);
emitter.setScale(-2, 2, 1, 1, 3000, Phaser.Easing.Sinusoidal.InOut, true);
emitter.gravity = 300;
emitter.start(false, 5000, 700, 50);
game.time.events.add(3000, destroyEmitter, this);
}
function tweens(cash) {
var bugs;
var index = 0;
var data;
var pos = [];
var tween;
var tweenData = { x: 0, y: 0 };
tween = game.make.tween(tweenData).to( { x: 100, y: 400 }, 2000, "Sine.easeInOut");
tween.yoyo(true);
data = tween.generateData(60);
bugs = game.add.group();
pos.push(new Phaser.Point(32, 0));
pos.push(new Phaser.Point(300, 100));
pos.push(new Phaser.Point(600, 70));
bugs.create(pos[0].x, pos[0].y, 'wasp');
bugs.create(pos[1].x, pos[1].y, 'wasp');
bugs.create(pos[2].x, pos[2].y, 'wasp');
tween.onUpdateCallback(function () {
bugs.getAt(0).x = pos[0].x + data[index].x;
bugs.getAt(0).y = pos[0].y + data[index].y;
bugs.getAt(1).x = pos[1].x + (data[index].x / 2);
bugs.getAt(1).y = pos[1].y + data[index].y;
// Inverse one of the values
bugs.getAt(2).x = pos[2].x - data[index].x;
bugs.getAt(2).y = pos[2].y + data[index].y;
index++;
if (index === data.length)
{
index = 0;
}
});
tween.start();
}
function destroyEmitter() {
console.log(emitter);
emitter.destroy();
tweens();
}
As you can see, I have made the particle-animation. Such steps need to be taken:
Particle-animation should be cached in the form of a set of shots (textures)
Particle-animation should be deleted. I have already done it (by means of ‘destroy‘)
Instead of the particle animation sprite animation should be realized by means of the function tweens using received textures
and passing these textures as the argument of the function tweens
Any refractoring is welcome.
In Phaser, the emitter particles are of the relatively simple DisplayObject class which do not support animations like the Phaser.Sprite does. Btw I don't know if using tweens is the best way to animate particles, because I suspect it will be heavy on CPU usage, using Sprite animations on the other hand is a bit more "light weight".
But either way, you could create a custom particle class which contains the code for your particle animation (using tweens, animations, timers, whatever) and then set that custom class as the emitter.particleClass, see a code example in link below:
http://codetuto.com/2016/02/phaser-animated-particles/