Pixi.js Movement 2
by jolaleye
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/pixi.js/4.8.1/pixi.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js"></script>
CSS
body {
margin: 0;
padding: 0;
overflow: hidden;
}
canvas {
display: block;
}
JavaScript
const app = new PIXI.Application({
transparent: true,
antialias: true,
});
document.body.appendChild(app.view);
const resize = () => {
app.renderer.resize(window.innerWidth, window.innerHeight);
}
app.renderer.autoResize = true;
window.addEventListener('resize', resize);
resize();
const getDistance = (x1, x2, y1, y2) => {
return {
x: x2 - x1,
y: y2 - y1,
total: Math.sqrt(Math.pow((x2 - x1), 2) + Math.pow((y2 - y1), 2)),
}
};
const lerp = (v0, v1, t) => (
((1 - t) * v0) + (t * v1)
);
const angularLerp = (a0, a1, t) => {
const max = Math.PI * 2;
const da = (a1 - a0) % max;
const shortestAngle = ((2 * da) % max) - da;
return a0 + (shortestAngle * t);
};
class PlayerManager {
constructor() {
this.local = { direction: 0, pos: { x: 100, y: 100 } };
this.origin = { direction: 0, pos: { x: 100, y: 100 } };
this.next = { direction: 0, pos: { x: 100, y: 100 } };
this.player = new PIXI.Graphics();
this.player.beginFill(0x9842f4).drawRect(-50, -50, 100, 100);
}
predict(target) {
this.origin = _.cloneDeep(this.local);
const distance = getDistance(this.local.pos.x, target.x, this.local.pos.y, target.y);
this.next.direction = Math.atan2(distance.y, distance.x);
let dx = 7 * Math.cos(this.next.direction);
let dy = 7 * Math.sin(this.next.direction);
if (distance.total < 100) {
dx *= distance.total / 100;
dy *= distance.total / 100;
}
this.next.pos.x = this.local.pos.x + dx;
this.next.pos.y = this.local.pos.y + dy;
}
interpolate(delta) {
if (!this.local || !this.origin || !this.next) return;
// interpolate between the origin and next states
this.local.pos.x = lerp(this.origin.pos.x, this.next.pos.x, delta);
this.local.pos.y = lerp(this.origin.pos.y, this.next.pos.y, delta);
this.local.direction = angularLerp(this.origin.direction, this.next.direction, delta);
}
update() {
this.player.position.set(this.local.pos.x,...