uradibou/src/main.js
2026-04-11 03:54:43 +02:00

106 lines
3.4 KiB
JavaScript

// description: This example demonstrates how to use a Container to group and manipulate multiple sprites
import { Application, Assets, Container, Sprite } from "pixi.js";
const app = new Application();
async function setup() {
await app.init({ background: "#1099bb", resizeTo: window });
document.body.appendChild(app.canvas);
}
async function preload() {
const assets = [
{
alias: "background",
src: "assets/img/background1.jpg",
},
{
alias: "opinator",
src: "assets/img/opinator.avif",
},
];
await Assets.load(assets);
}
class Opinator {
constructor(gameContainer) {
this.inMove = false; // indicates if player has grabed the wire (is mouse down)
this.currentScore = 0;
this.pixelGoalScore = undefined;
this.goalScore = 10; // goal to match, measured in play area, 10 = moving the mouse on the equivalent of 10 play areas
this.lastMousePos = undefined; // use to compute the travelled distance
this.won = false;
const backgroundSprite = Sprite.from("opinator");
this.pixelGoalScore = backgroundSprite.width * this.goalScore; // beware of resize mid game
backgroundSprite.eventMode = "static";
backgroundSprite.on("pointerdown", (event) => {
console.log("Opinator grabbed");
this.inMove = true;
this.lastMousePos = event.client.clone();
});
backgroundSprite.on("pointerupoutside", () => {
console.log("Opinator released");
this.inMove = false;
this.lastMousePos = undefined;
});
backgroundSprite.on("pointerup", () => {
console.log("Opinator released");
this.inMove = false;
this.lastMousePos = undefined;
});
backgroundSprite.on("mousemove", (event) => {
if (this.inMove && !this.won) {
const newMousePos = event.client;
const progress = Math.sqrt(
(newMousePos.x - this.lastMousePos.x) ** 2 +
(newMousePos.y - this.lastMousePos.y) ** 2,
);
if (progress > 0) {
this.lastMousePos = newMousePos.clone();
this.currentScore += progress;
console.log(
"mouse move, current score",
this.currentScore,
"goal",
this.pixelGoalScore,
);
if (this.pixelGoalScore < this.currentScore) {
console.log("game won");
this.won = true;
}
} //else ignore, not enough move to get some distance
}
});
gameContainer.addChild(backgroundSprite);
}
}
(async () => {
await setup();
await preload();
const background = Sprite.from("background");
if (app.screen.width > app.screen.height) {
background.width = app.screen.width * 1.2;
background.scale.y = background.scale.x;
} else {
background.height = app.screen.height * 1.2;
background.scale.x = background.scale.y;
}
app.stage.addChild(background);
const gameContainter = new Container();
const opinator = new Opinator(gameContainter);
app.stage.addChild(gameContainter);
})();