JSFiddle - React, Tailwind, and code Playground
HTML
<script src="https://pixijs.download/dev/pixi.js"></script>
JavaScript
const graphics = new PIXI.Graphics();
const app = new PIXI.Application();
const movementSpeed = 150;
const stage = app.stage;
const blocks = [];
stage.addChild(graphics);
class Block {
constructor(position=[0, 0], direction=[0, 0]) {
this.width = 20;
this.position = position;
this.prevPosition = position;
this.direction = direction;
}
render (alpha = 0) {
// currentState * alpha + previousState * ( 1.0 - alpha );
let offsetX = (this.position[0] * alpha) + (this.prevPosition[0] * (1 - alpha));
let offsetY = (this.position[1] * alpha) + (this.prevPosition[1] * (1 - alpha));
graphics.drawRect(offsetX, offsetY, this.width, this.width);
}
update (delta = 0) {
this.prevPosition = this.position;
this.position = this.calculateNewPosition(delta);
}
calculateNewPosition (delta) {
let movementOffset = movementSpeed * (delta / 1000);
return [
this.position[0] + (movementOffset * this.direction[0]),
this.position[1] + (movementOffset * this.direction[1])
];
}
};
function render (delta) {
graphics.clear();
graphics.beginFill(0xFF0000);
blocks.forEach((block) => block.render(delta));
graphics.endFill();
};
function update (delta) {
blocks.forEach((block) => block.update(delta));
};
function changeDirection (direction) {
blocks.forEach((block) => { block.direction = direction });
}
const fps = 30; // Frames per second
const frameDuration = 1000 / fps; // Maximum time per frame.
const maxFrameDelta = 1000; // Upper limit on how long the frame takes to render.
let previousTimestamp = 0; // Last timestamp.
let accumulator = 0; // Remainder of time that we could not simulate in our fixed-step physics. (used to smooth out temporal aliasing)
function gameLoop(timestamp = 0) {
requestAnimationFrame(gameLoop);
//Calculate the time...