JSFiddle - React, Tailwind, and code Playground
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/pixi.js/4.5.6/pixi.min.js"></script>
JavaScript
// define gamne variables
const appWidth = window.innerWidth;
const appHeight = window.innerHeight;
const paddleWidth = 50;
const paddleHeight = 10;
const ballSize = 5;
const appWidthHalf = appWidth / 2;
const appHeightHalf = appHeight / 2;
const paddleWidthHalf = paddleWidth / 2;
const pongColor = 0x57dfbf;
const computerPositionX = appWidthHalf - paddleWidthHalf;
const computerPositionY = 50;
const playerPositionX = computerPositionX;
const playerPositionY = appHeight - computerPositionY - paddleHeight;
const ballPositionX = appWidthHalf;
const ballPositionY = appHeightHalf;
const playerSpeed = 4;
const computerSpeed = 4;
const ballSpeed = 3;
// Setup the ticker and the root stage PIXI.Container.
const app = new PIXI.Application(appWidth, appHeight, {
antialias: false,
transparent: false,
resolution: 1,
});
function Paddle(x, y, width, height) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
this.x_speed = 0;
this.y_speed = 0;
}
Paddle.prototype.render = function renderPaddle() {
this.graphics = new PIXI.Graphics();
this.graphics.beginFill(pongColor);
this.graphics.drawRect(this.x, this.y, this.width, this.height);
this.graphics.endFill();
app.stage.addChild(this.graphics);
};
Paddle.prototype.move = function (x, y) {
this.x += x;
this.y += y;
this.x_speed = x;
this.y_speed = y;
if (this.x < 0) {
this.x = 0;
this.x_speed = 0;
} else if (this.x + this.width > appWidth) {
this.x = appWidth - this.width;
this.x_speed = 0;
}
};
function Player() {
this.paddle = new Paddle(playerPositionX, playerPositionY, paddleWidth, paddleHeight);
}
Player.prototype.render = function renderPlayer() {
this.paddle.render();
};
Player.prototype.update = function () {
for (const key in keysDown) {
const value = Number(key);
if (value === 37) {
this.paddle.move(-playerSpeed, 0);
} else if (value === 39) {
this.paddle.move(playerSpeed, 0);
} else {
...