From ceb204f26b8fa5da88e603e05f7325ddadd95b62 Mon Sep 17 00:00:00 2001 From: jxnshi Date: Sun, 8 Dec 2024 18:47:00 +0100 Subject: [PATCH] Normalized movements --- public/cattoland/cattoland.js | 51 ++++++++++++++++++++--------------- 1 file changed, 29 insertions(+), 22 deletions(-) diff --git a/public/cattoland/cattoland.js b/public/cattoland/cattoland.js index 550f639..56c7bf0 100644 --- a/public/cattoland/cattoland.js +++ b/public/cattoland/cattoland.js @@ -41,6 +41,10 @@ let entities = []; let player; +const event_strength = (event) => { + return events.get(event) ? 1 : 0; +}; + const image_load = (images, path) => { let image = new Image(); image.src = path; @@ -100,6 +104,10 @@ const catto_init = () => { return entity; }; +const vec_length = (x, y) => { + return Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2)); +}; + const main = () => { image_load(images, "cattoland/catto.png"); image_load(images, "cattoland/shadow.png"); @@ -128,37 +136,28 @@ const main = () => { const loop = (delta) => { { // Events. - let moving = false; + let dir_x = event_strength("KeyD") - event_strength("KeyA"); + let dir_y = event_strength("KeyS") - event_strength("KeyW"); - if (events.get("KeyW") === "down") { - player.y -= player.speed; - moving = true; - } + let dir_len = vec_length(dir_x, dir_y); - if (events.get("KeyA") === "down") { - player.x -= player.speed; - moving = true; + if (dir_len !== 0) { + let unit_x = dir_x / dir_len; + let unit_y = dir_y / dir_len; - if (player.anim !== "move_left") { - entity_play_anim(player, "move_left"); - } + player.x += player.speed * unit_x; + player.y += player.speed * unit_y; } - if (events.get("KeyS") === "down") { - player.y += player.speed; - moving = true; + if (dir_x < 0 && player.anim !== "move_left") { + entity_play_anim(player, "move_left"); } - if (events.get("KeyD") === "down") { - player.x += player.speed; - moving = true; - - if (player.anim !== "move_right") { - entity_play_anim(player, "move_right"); - } + if (dir_x > 0 && player.anim !== "move_right") { + entity_play_anim(player, "move_right"); } - if (!moving) { + if (dir_x === 0 && dir_y === 0) { if (player.anim === "move_right") { entity_play_anim(player, "idle_right"); } @@ -166,6 +165,14 @@ const loop = (delta) => { if (player.anim === "move_left") { entity_play_anim(player, "idle_left"); } + } else { + if (player.anim === "idle_right") { + entity_play_anim(player, "move_right"); + } + + if (player.anim === "idle_left") { + entity_play_anim(player, "move_left"); + } } for (let entity of entities) { -- 2.49.0