Skip to content

Commit 7184e34

Browse files
committed
refactor: use composition over inheritance
1 parent 70e47b3 commit 7184e34

File tree

2 files changed

+24
-13
lines changed

2 files changed

+24
-13
lines changed

src/main.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,7 @@ export async function setup(el: HTMLElement, stageDefinition: StageDefinition) {
4949
});
5050
const player = new Player(cx, bunnyTexture);
5151
app.ticker.add((ticker) => player.tick(cx, ticker));
52-
app.stage.addChild(player);
52+
app.stage.addChild(player.sprite);
5353

5454
let cleanup: undefined | (() => void) = undefined;
5555
app.ticker.add(() => {

src/player.ts

Lines changed: 23 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,8 @@ enum Inputs {
1111
Up = 2,
1212
Ctrl = 3,
1313
}
14-
export class Player extends Sprite {
14+
export class Player {
15+
sprite: Sprite;
1516
holdingKeys: { [key in Inputs]?: boolean };
1617
vx: number;
1718
vy: number;
@@ -21,36 +22,46 @@ export class Player extends Sprite {
2122
ability: AbilityControl;
2223
constructor(
2324
cx: Context,
24-
superOptions?: SpriteOptions | Texture,
25+
spriteOptions?: SpriteOptions | Texture,
2526
thisOptions?: {
2627
ability?: AbilityInit;
2728
},
2829
) {
29-
super(superOptions);
30+
this.sprite = new Sprite(spriteOptions);
3031
// Center the sprite's anchor point
31-
this.anchor.set(0.5, 1);
32+
this.sprite.anchor.set(0.5, 1);
33+
// todo: 初期座標をフィールドとともにどこかで決定
34+
this.sprite.x = 2 * cx.blockSize;
35+
this.sprite.y = 2 * cx.blockSize;
36+
this.sprite.width = c.playerWidth * cx.blockSize;
37+
this.sprite.height = c.playerHeight * cx.blockSize;
38+
3239
// Move the sprite to the center of the screen
3340
document.addEventListener("keydown", (event) =>
3441
this.handleInput(cx, event, true),
3542
);
3643
document.addEventListener("keyup", (event) =>
3744
this.handleInput(cx, event, false),
3845
);
39-
40-
// todo: 初期座標をフィールドとともにどこかで決定
41-
this.x = 2 * cx.blockSize;
42-
this.y = 2 * cx.blockSize;
43-
44-
this.width = c.playerWidth * cx.blockSize;
45-
this.height = c.playerHeight * cx.blockSize;
46-
4746
this.ability = new AbilityControl(cx, thisOptions?.ability);
4847
this.vx = 0;
4948
this.vy = 0;
5049
this.onGround = false;
5150
this.jumpingBegin = null;
5251
this.holdingKeys = {};
5352
}
53+
get x() {
54+
return this.sprite.x;
55+
}
56+
set x(v) {
57+
this.sprite.x = v;
58+
}
59+
get y() {
60+
return this.sprite.y;
61+
}
62+
set y(v) {
63+
this.sprite.y = v;
64+
}
5465
getCoords(cx: Context) {
5566
const x = Math.floor(this.x / cx.blockSize);
5667
const y = Math.round(this.y / cx.blockSize) - 1; // it was not working well so take my patch

0 commit comments

Comments
 (0)