ujs/test/js/game.example.js

63 lines
1.4 KiB
JavaScript
Raw Normal View History

2023-04-06 14:44:41 +03:00
import { App } from './app.js';
2023-04-06 18:46:01 +03:00
import { Scene, SceneLayer } from './scene.js';
2023-04-23 19:13:53 +03:00
import { Rect, StrokeRect, Sprite } from './objects.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', [
new Sprite('compass.png', 15, 15),
new Sprite('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
let app = new App(document.querySelector('canvas'), 400, 400);
// 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;
}
});