ujs/test/js/game.example.js

61 lines
1.4 KiB
JavaScript
Raw Normal View History

2023-04-30 17:47:06 +03:00
import { App, Scene, SceneLayer, Rect, StrokeRect, Sprite } from './engine.js';
2023-04-06 14:44:41 +03:00
2023-04-23 19:13:53 +03:00
// init player
2023-04-23 17:01:17 +03:00
let Player = {
2023-04-23 19:13:53 +03:00
x: 400 / 2 - 5,
y: 400 / 2 - 5,
2023-04-23 17:01:17 +03:00
rect: null,
};
Player.rect = new Rect(Player.x, Player.y, 10, 10, 'black');
Player.rect.ticker = () => {
Player.rect.y = Player.y;
Player.rect.x = Player.x;
};
2023-04-23 19:13:53 +03:00
// init scene layers
let layerBg = new SceneLayer('background', [
2023-04-06 18:46:01 +03:00
new Rect(50, 50, 100, 100, 'red'),
new StrokeRect(150, 150, 40, 40, 'green', 'blue', 1),
2023-04-23 19:13:53 +03:00
]);
2023-04-23 17:01:17 +03:00
2023-04-23 19:13:53 +03:00
let layerHud = new SceneLayer('hud', [
2023-04-30 17:47:06 +03:00
new Sprite('/assets/compass.png', 15, 15),
new Sprite('/assets/compass-arrow.png', 27, 21),
2023-04-06 18:46:01 +03:00
]);
2023-04-23 19:13:53 +03:00
2023-04-23 19:41:18 +03:00
let layerInstances = new SceneLayer('Instances', [Player.rect], { debug: true });
2023-04-23 19:13:53 +03:00
// init app
2023-04-30 17:47:06 +03:00
let app = new App(400, 400);
2023-04-23 19:13:53 +03:00
// init scene
let firstScene = new Scene(app.canvas, app.context, 400, 400);
firstScene.addLayer(layerBg);
firstScene.addLayer(layerInstances);
firstScene.addLayer(layerHud);
2023-04-06 18:46:01 +03:00
app.scene = firstScene;
// add app view in document
2023-04-06 14:44:41 +03:00
window.addEventListener('DOMContentLoaded', () => {
2023-04-06 18:46:01 +03:00
document.body.appendChild(app.view);
2023-04-06 14:44:41 +03:00
});
2023-04-23 17:01:17 +03:00
2023-04-23 19:13:53 +03:00
// player key press listener
2023-04-23 17:01:17 +03:00
document.addEventListener('keydown', (e) => {
switch (e.code) {
case 'ArrowUp':
Player.y -= 1;
break;
case 'ArrowDown':
Player.y += 1;
break;
case 'ArrowLeft':
Player.x -= 1;
break;
case 'ArrowRight':
Player.x += 1;
break;
}
});