Hi,
I’m trying to move a sprite around following a path which is calculated programmatically.
In the real application I would get the next set of points from an ajax call let’s say every 1 sec. If you run this simplified version of code you’ll see that, at the beginning, the sprite jump here and there for then stabilize. How can I stop this inconsistent movements?
I’m not sure this is the right approach, I spent quite a bit of time trying to figure out how to go with this, in this solution I used a path and a tween. Because I want the speed to be constant I had to use timeScale which looks also hacky…
I would really appreciate if someone could help…
Thanks
var config = {
type: Phaser.WEBGL,
width: 800,
height: 600,
backgroundColor: '#2d2d2d',
parent: 'phaser-example',
scene: {
preload: preload,
create: create,
update: update
}
};
const turns = [
[306, 100, 324, 100, 354, 100, 396, 100, 450, 100],
[496, 128, 520, 177, 515, 231, 482, 274, 431, 293],
[378, 282, 339, 246, 325, 194, 340, 142, 380, 106],
[433, 97, 483, 117, 515, 161, 519, 214, 495, 262],
[448, 290, 394, 289, 349, 259, 326, 211, 332, 157],
[366, 115, 416, 96, 470, 103, 536, 110, 613, 119],
[675, 167, 723, 228, 779, 298, 780, 378, 780, 468]
];
let car;
let tween;
let frameSlot = 0;
let _this;
let graphics;
const maxPoints = 5;
let game = new Phaser.Game(config);
function preload() {
this.load.image('car', 'assets/sprites/car90.png');
}
function create() {
_this = this;
graphics = this.add.graphics();
curve = new Phaser.Curves.Spline(getPoints());
path = { t: 0, vec: new Phaser.Math.Vector2() };
car = this.add.image(300, 100, 'car');
tween = this.tweens.add({
targets: path,
t: 1,
x: 306,
y: 100,
ease: 'Sine.easeIn',
duration: 200000,
paused: true
});
_this.time.addEvent({ delay: 500, callback: nextPoint });
tween.play();
}
function update() {
graphics.clear();
curve.getPoint(path.t, path.vec);
var angle = Math.atan2(path.vec.y - car.y, path.vec.x - car.x);
car.rotation = angle;
car.setPosition(path.vec.x, path.vec.y);
}
function nextPoint() {
frameSlot += 1;
curve.addPoints(getPoints());
tween.timeScale = 100 / frameSlot;
if (hasPoints()) {
_this.time.addEvent({ delay: 500, callback: nextPoint });
}
}
function getPoints() {
let points = turns[frameSlot];
console.log(points);
return points;
}
function hasPoints() {
return frameSlot < (turns.length - 1);
}