Add whole body sprites with idle and shoot poses (#34)

This commit is contained in:
lucas authored and GitHub committed 2026-05-04 19:29:39 +02:00
1 parent c0886a7daf
commit db3781c11d
19 files changed
+224 -182

No files matched your search

Binary file not shown.

After

Width:  |  Height:  |  Size: 493 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 971 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.0 MiB

+1 -1
View File
@@ -10,7 +10,7 @@ import {
vec,
Vector,
} from "excalibur";
import { gravitationalConstant } from "../utils/physicsConstant";
import { gravitationalConstant } from "../configs/physicsConstant";
import { Parabola as ParabolaJSON } from "../jsonTypes";
import { BallClock } from "../Timers/BallClock";
import { BaseActor } from "./BaseActor";
+55 -122
View File
@@ -1,144 +1,77 @@
import {
Actor,
ActorArgs,
Color,
Engine,
Graphic,
GraphicsGroup,
Line,
Polygon,
vec,
} from "excalibur";
import { pixelsPerMeter } from "../utils/physicsConstant";
import { jitterVector, randomInteger } from "../utils/randomUtils";
import { ActorArgs, Engine, Sprite, vec } from "excalibur";
import { pixelsPerMeter } from "../configs/physicsConstant";
import { randomInteger } from "../utils/randomUtils";
import { getImage } from "../imageLoader";
import { Clock } from "../Timers/Clock";
import { BaseActor } from "./BaseActor";
import { ChampionName, champions } from "./champions";
const jiggleTime = 500;
type Facing = "left" | "right";
export class Champion extends Actor {
private _graphic: Graphic = null!;
export class Champion extends BaseActor {
facing: Facing;
championName: ChampionName;
private _jiggleTimer = randomInteger(0, 1000);
constructor(actorArgs: ActorArgs) {
constructor(actorArgs: ActorArgs, facing: Facing, name: ChampionName) {
super(actorArgs);
this.facing = facing;
this.championName = name;
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
onInitialize(_engine: Engine): void {
const height = 1.4 * pixelsPerMeter;
const width = 0.4 * pixelsPerMeter;
const waistHeight = 0.3 * pixelsPerMeter;
const jitterMag = 0.1 * pixelsPerMeter;
const headSize = 0.5 * pixelsPerMeter;
const championConfig = champions[this.championName];
const bodyPoints = [
jitterVector(vec(-width / 2, waistHeight), jitterMag),
jitterVector(vec(-width / 2, height), jitterMag),
jitterVector(vec(width / 2, height), jitterMag),
jitterVector(vec(width / 2, waistHeight), jitterMag),
];
const height = championConfig.height * pixelsPerMeter;
const width = 0.8 * pixelsPerMeter;
const bodyGraphic = new Polygon({
points: bodyPoints,
color: this.color,
this.anchor = vec(0.5, 0.95);
const flipHorizontal = this.facing === "right";
const idleImage = getImage(`${this.championName}_idle`);
const shootImage = getImage(`${this.championName}_shoot`);
const idleGraphic = new Sprite({
image: idleImage,
flipHorizontal,
destSize: {
width: width,
height: width + height,
},
});
const leftLeg = new Line({
start: bodyPoints[0],
end: vec(bodyPoints[0].x, 0),
thickness: 5,
color: Color.Black,
const shootGraphic = new Sprite({
image: shootImage,
flipHorizontal,
destSize: {
width: width,
height: width + height,
},
});
const rightLeg = new Line({
start: bodyPoints[3],
end: vec(bodyPoints[3].x, 0),
thickness: 5,
color: Color.Black,
});
this.graphics.add("idle", idleGraphic);
this.graphics.add("shoot", shootGraphic);
this.setPose("idle");
const headPoints = [
jitterVector(vec(-headSize / 2, 0), jitterMag),
jitterVector(vec(-headSize / 2, headSize), jitterMag),
jitterVector(vec(headSize / 2, headSize), jitterMag),
jitterVector(vec(headSize / 2, 0), jitterMag),
];
const headGraphic = new Polygon({
points: headPoints,
color: this.color,
});
this.rotation = (Math.PI / 180) * 1;
this.anchor = vec(0.5, 1);
this._graphic = new GraphicsGroup({
members: [
{ graphic: leftLeg, offset: vec(0, -waistHeight) },
{ graphic: rightLeg, offset: vec(0, -waistHeight) },
{ graphic: bodyGraphic, offset: vec(-width / 2, -height) },
{
graphic: headGraphic,
offset: vec(-headSize / 2, -height - headSize / 2),
},
{
graphic: smileEyeGraphic.clone(),
offset: vec(-headSize / 4, -height),
},
{
graphic: smileEyeGraphic.clone(),
offset: vec(headSize / 4, -height),
},
],
useAnchor: false,
});
this.graphics.add(this._graphic);
this.rotation = (Math.PI / 180) * 5;
this._setupJiggle();
}
update(_engine: Engine, elapsed: number): void {
this._jiggle(elapsed);
}
private _setupJiggle(): void {
const jiggleClock = new Clock();
jiggleClock.start(randomInteger(0, 1000));
private _jiggle(elapsed: number): void {
this._jiggleTimer += elapsed;
if (this._jiggleTimer > jiggleTime) {
this._jiggleTimer -= jiggleTime;
// Repeat by starting when stopping with a new random duration.
jiggleClock.on("stop", () => {
this.rotation = -this.rotation;
}
jiggleClock.start(randomInteger(500, 800));
});
this.addClock(jiggleClock);
}
setPose(pose: "idle" | "shoot"): void {
this.graphics.use(pose);
}
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const _crossEyeGraphic = new GraphicsGroup({
members: [
new Line({
start: vec(-5, -5),
end: vec(5, 5),
color: Color.Black,
thickness: 3,
}),
new Line({
start: vec(5, -5),
end: vec(-5, 5),
color: Color.Black,
thickness: 3,
}),
],
});
const smileEyeGraphic = new GraphicsGroup({
members: [
new Line({
start: vec(-5, 5),
end: vec(5, -5),
color: Color.Black,
thickness: 3,
}),
new Line({
start: vec(5, -5),
end: vec(10, 5),
color: Color.Black,
thickness: 3,
}),
],
});
+1 -1
View File
@@ -9,7 +9,7 @@ import {
Polygon,
vec,
} from "excalibur";
import { pixelsPerMeter } from "../utils/physicsConstant";
import { pixelsPerMeter } from "../configs/physicsConstant";
export const defaultCupConfiguration = {
cupColor: Color.Red,
+1 -1
View File
@@ -1,5 +1,5 @@
import { Actor, Color, Engine, Graphic, Rectangle } from "excalibur";
import { groundHeight } from "../utils/physicsConstant";
import { groundHeight } from "../configs/sceneConfiguration";
export const groundColor = Color.Gray;
-10
View File
@@ -7,16 +7,6 @@ import {
Polygon,
vec,
} from "excalibur";
import { pixelsPerMeter } from "../utils/physicsConstant";
export const defaultTableConfiguration = {
color: Color.Brown,
width: 2.44 * pixelsPerMeter,
height: 0.7 * pixelsPerMeter,
thickness: 0.15 * pixelsPerMeter,
legOffset: 0.15 * pixelsPerMeter,
legThickness: 0.15 * pixelsPerMeter,
};
export interface TableConfiguration {
readonly color: Color;
@@ -0,0 +1,21 @@
export type ChampionName = "lucas" | "berset";
export interface ChampionConfig {
name: ChampionName;
height: number;
}
const lucas: ChampionConfig = {
name: "lucas",
height: 1.4,
};
const berset: ChampionConfig = {
name: "berset",
height: 1.5,
};
export const champions: Record<ChampionName, ChampionConfig> = {
lucas,
berset,
};
+1 -1
View File
@@ -9,7 +9,7 @@ export class BaseScene extends Scene {
this._clocks.forEach((clock) => clock.update(elapsed));
}
protected addClock(timer: Clock): void {
addClock(timer: Clock): void {
this._clocks.push(timer);
}
+63 -25
View File
@@ -1,22 +1,25 @@
import { Connection, MatchMessageEvent } from "../Connection";
import { Ground, groundColor } from "../GameElements/Ground";
import {
defaultTableConfiguration,
Table as TableElement,
} from "../GameElements/Table";
import { Cup, defaultCupConfiguration } from "../GameElements/Cups";
import { Color, vec } from "excalibur";
import { Connection, MatchMessageEvent } from "../Connection";
import { Ball, defaultBallConfiguration, Parabola } from "../GameElements/Ball";
import { groundHeight } from "../utils/physicsConstant";
import { Champion } from "../GameElements/Champion";
import { randomColor } from "../utils/randomUtils";
import { colorDistance } from "../utils/colorUtils";
import { Cup, defaultCupConfiguration } from "../GameElements/Cups";
import { Ground, groundColor } from "../GameElements/Ground";
import { Table as TableElement } from "../GameElements/Table";
import { MatchState } from "../MatchState";
import { Action, Table } from "../jsonTypes";
import { assertNotNull } from "../utils/assertUtils";
import { Clock } from "../Timers/Clock";
import {
championPositions,
groundHeight,
tableConfiguration,
} from "../configs/sceneConfiguration";
import { Action, Table } from "../jsonTypes";
import { assertNotNull, assertNull } from "../utils/assertUtils";
import { colorDistance } from "../utils/colorUtils";
import { randomColor, randomInteger } from "../utils/randomUtils";
import { BaseScene } from "./BaseScene";
const speedUpFactor = 3;
export class MatchScene extends BaseScene {
private _ground: Ground = null!;
private _table: TableElement = null!;
@@ -27,6 +30,8 @@ export class MatchScene extends BaseScene {
private _matchClock = new Clock();
private _playingHistoryPromise?: Promise<void>;
constructor(private _connection: Connection) {
super();
@@ -34,11 +39,11 @@ export class MatchScene extends BaseScene {
this._connection.on("match-message", (e: MatchMessageEvent) => {
if (!this.isInitialized) {
this.once("initialize", () => this._playFroMatchState(e.matchState));
this.once("initialize", () => this._playFromMatchState(e.matchState));
return;
}
this._playFroMatchState(e.matchState);
this._playFromMatchState(e.matchState);
});
}
@@ -51,7 +56,7 @@ export class MatchScene extends BaseScene {
this._table = new TableElement(
{ pos: vec(0, groundHeight) },
defaultTableConfiguration,
tableConfiguration,
);
this.add(this._table);
@@ -75,15 +80,16 @@ export class MatchScene extends BaseScene {
this._cups.push(cup);
});
const championPositions = [
...[50, 150, 250].map((v) => -v - tableHalfWidth),
...[50, 150, 250].map((v) => v + tableHalfWidth),
];
championPositions.forEach((offsetX) => {
const champion = new Champion({
color: randomNonGroundColor(),
pos: vec(offsetX, groundHeight),
});
championPositions.forEach((offsetX, index) => {
const facing = index < 3 ? "right" : "left";
const champion = new Champion(
{
color: randomNonGroundColor(),
pos: vec(offsetX, groundHeight),
},
facing,
randomInteger(0, 2) === 0 ? "berset" : "lucas",
);
this.add(champion);
this._champions.push(champion);
});
@@ -91,19 +97,47 @@ export class MatchScene extends BaseScene {
this._ball = new Ball({}, defaultBallConfiguration);
}
private async _playFroMatchState(state: MatchState): Promise<void> {
private async _playFromMatchState(state: MatchState): Promise<void> {
const promise = this._playingHistoryPromise;
if (promise != null) {
const previousMatchClockSpeed = this._matchClock.speedFactor;
const previousBallSpeed = this._ball.clock.speedFactor;
this._matchClock.speedFactor *= speedUpFactor;
this._ball.clock.speedFactor *= speedUpFactor;
await promise;
this._matchClock.speedFactor = previousMatchClockSpeed;
this._ball.clock.speedFactor = previousBallSpeed;
}
assertNull(this._playingHistoryPromise);
let resolver: () => void;
this._playingHistoryPromise = new Promise(
(resolve) => (resolver = resolve),
);
for (const actionOrTable of state.matchStateRaw.history) {
if ("cupsA" in actionOrTable) {
this._updateFromTableState(actionOrTable);
await this._matchClock.startAndWait(2000);
} else {
this.updateActorVisibility(this._ball, true);
const currentChampion = this._getCurrentChampion(actionOrTable.turn);
currentChampion.setPose("shoot");
this._updateFromActionState(actionOrTable);
await this._ball.clock.whenEnd();
currentChampion.setPose("idle");
await this._matchClock.startAndWait(1000);
this.updateActorVisibility(this._ball, false);
}
}
this._playingHistoryPromise = undefined;
resolver!();
}
private _updateFromTableState(table: Table): void {
@@ -119,6 +153,10 @@ export class MatchScene extends BaseScene {
const parabola = Parabola.fromJSON(action.parabola);
this._ball.startParabolaAnimation(parabola);
}
private _getCurrentChampion(turn: "a" | "b"): Champion {
return turn === "a" ? this._champions[0] : this._champions[3];
}
}
function randomNonGroundColor(): Color {
+3 -3
View File
@@ -1,6 +1,6 @@
import { Ball, Parabola } from "../GameElements/Ball";
import { assertNotNull } from "../utils/assertUtils";
import { groundHeight } from "../utils/physicsConstant";
import { groundHeight } from "../configs/sceneConfiguration";
import { Clock } from "./Clock";
export class BallClock extends Clock {
@@ -24,8 +24,8 @@ export class BallClock extends Clock {
assertNotNull(this._parabola);
assertNotNull(this._elapsedTime);
const newPosition = this._parabola.position(this._elapsedTime);
assertNotNull(this._elapsedTimeMS);
const newPosition = this._parabola.position(this._elapsedTimeMS);
// Collide with ground
const yMin = groundHeight - this._ball.configuration.radius;
+14 -14
View File
@@ -5,18 +5,19 @@ export const TimerEvents = {
start: Event,
stop: Event,
end: Event,
reset: Event,
};
export class Clock extends Evented<typeof TimerEvents> {
private _running: boolean = false;
protected _elapsedTime: number | null = null;
protected _elapsedTimeMS: number | null = null;
private _duration?: number;
private _durationMS?: number;
speedFactor = 1;
constructor(duration?: number) {
super();
this._duration = duration;
this._durationMS = duration;
}
get running(): boolean {
@@ -26,7 +27,7 @@ export class Clock extends Evented<typeof TimerEvents> {
start(duration?: number): void {
this.reset();
if (duration != null) {
this._duration = duration;
this._durationMS = duration;
}
this._running = true;
this.emit("start", {});
@@ -34,14 +35,13 @@ export class Clock extends Evented<typeof TimerEvents> {
stop(): void {
this._running = false;
this._elapsedTime = null;
this._elapsedTimeMS = null;
this.emit("stop", {});
}
reset(): void {
this._running = false;
this._elapsedTime = null;
this.emit("reset", {});
this._elapsedTimeMS = null;
}
async whenEnd(): Promise<void> {
@@ -58,17 +58,17 @@ export class Clock extends Evented<typeof TimerEvents> {
update(elapsed: number): void {
if (!this.running) {
assertNull(this._elapsedTime);
assertNull(this._elapsedTimeMS);
return;
}
if (this._elapsedTime == null) {
this._elapsedTime = 0;
if (this._elapsedTimeMS == null) {
this._elapsedTimeMS = 0;
}
this._elapsedTime += elapsed;
this._elapsedTimeMS += elapsed * this.speedFactor;
if (this._duration != null) {
if (this._elapsedTime > this._duration) {
if (this._durationMS != null) {
if (this._elapsedTimeMS > this._durationMS) {
this.stop();
this.emit("end", {});
}
@@ -1,3 +1,2 @@
export const pixelsPerMeter = 100;
export const gravitationalConstant = 9.81 * pixelsPerMeter;
export const groundHeight = 0;
@@ -0,0 +1,27 @@
import { Color } from "excalibur";
import { pixelsPerMeter } from "./physicsConstant";
export const tableConfiguration = {
color: Color.Brown,
width: 2.44 * pixelsPerMeter,
height: 0.7 * pixelsPerMeter,
thickness: 0.15 * pixelsPerMeter,
legOffset: 0.15 * pixelsPerMeter,
legThickness: 0.15 * pixelsPerMeter,
};
export const groundHeight = 0;
export const championDistanceFromTable = 0.5 * pixelsPerMeter;
export const championGap = 0.8 * pixelsPerMeter;
const championDistances = [
championDistanceFromTable,
championDistanceFromTable + championGap,
championDistanceFromTable + 2 * championGap,
];
export const championPositions = [
...championDistances.map((v) => -v - tableConfiguration.width / 2),
...championDistances.map((v) => v + tableConfiguration.width / 2),
];
+26
View File
@@ -0,0 +1,26 @@
import { ImageSource } from "excalibur";
import { assertNotNull } from "./utils/assertUtils";
const imageStrings = [
"lucas_idle.png",
"lucas_shoot.png",
"berset_idle.png",
"berset_shoot.png",
];
export const images = new Map<string, ImageSource>(
imageStrings.map((fileName) => [
fileName.replace(/\.[^/.]+$/, ""),
new ImageSource(`/assets/${fileName}`),
]),
);
export function getImage(key: string): ImageSource {
const image = images.get(key);
assertNotNull(image);
return image;
}
export async function loadImages(): Promise<void> {
await Promise.all([...images.values()].map((img) => img.load()));
}
+3
View File
@@ -7,6 +7,7 @@ import {
mockLobbyMessage,
MockSocket,
} from "./sockets/MockSocket";
import { loadImages } from "./imageLoader";
const urlParams = new URLSearchParams(window.location.search);
const mocked = urlParams.get("mock");
@@ -27,9 +28,11 @@ export const maxPlayers = 2;
scenes: { lobby: lobbyScene, match: matchScene },
backgroundColor: ex.Color.fromHex("23213b"),
});
game.toggleDebug();
await game.start();
await loadImages();
await game.goToScene("lobby");
connection.on("lobby-message", () => game.goToScene("lobby"));
+8 -3
View File
@@ -22,7 +22,12 @@ export class MockSocket
send(message: string): void {
if (message.includes("join")) {
this.sendToClient(JSON.stringify({ player: { id: 0, name: "Dubbel" } }));
this.sendToClient(
JSON.stringify({
messageType: "joinResponse",
messageContent: { client: { id: 0, name: "Dubbel" } },
}),
);
}
}
}
@@ -47,8 +52,8 @@ export function mockLobbyMessage(): string {
export function mockGameMessage(): string {
const matchUpdate = {
state: {
stateType: "match",
messageType: "matchState",
messsageContent: {
history: [
{
cupsA: [true, true, true],