Basic gamestate handling

This commit is contained in:
karl 2021-10-15 12:52:51 +02:00
parent 7a39b88854
commit 714681e044

View File

@ -84,8 +84,13 @@
last = timestamp(), last = timestamp(),
step = 1 / 60; step = 1 / 60;
var position_x = 100; const GameState = {
var position_y = 100; PLAYING: 0,
STARTSCREEN: 1
};
var current_gamestate = GameState.STARTSCREEN;
function frame() { function frame() {
now = timestamp(); now = timestamp();
@ -130,11 +135,20 @@
// Fixed time loop // Fixed time loop
function update(dt) { function update(dt) {
if (current_gamestate == GameState.PLAYING) {
player.position_y += player.velocity_y * dt; player.position_y += player.velocity_y * dt;
player.position_x += 100 * dt; player.position_x += 100 * dt;
// Gravity // Gravity
player.velocity_y += GRAVITY * dt; player.velocity_y += GRAVITY * dt;
// Lose condition
if (player.position_y > 400) {
die();
}
} else if (current_gamestate == GameState.STARTSCREEN) {
// Do nothing
}
} }
// Variable time render loop // Variable time render loop
@ -145,13 +159,33 @@
}); });
} }
// Jump
function die() {
current_gamestate = GameState.STARTSCREEN;
}
function restart() {
player.position_x = 100;
player.position_y = 100;
player.velocity_y = 0;
current_gamestate = GameState.PLAYING;
}
document.onmousedown = function (evt) { document.onmousedown = function (evt) {
if (current_gamestate == GameState.PLAYING) {
// Jump
player.velocity_y = -JUMP_VEL; player.velocity_y = -JUMP_VEL;
} else if (current_gamestate == GameState.STARTSCREEN) {
restart();
}
}; };
requestAnimationFrame(frame); requestAnimationFrame(frame);
</script> </script>
<div id="viewport"> <div id="viewport">
<div id="floor" style=" <div id="floor" style="
left:0px; left:0px;