What are the steps to implement character movement in a 2D game using JavaScript?

I'm having trouble getting the image with the ID "yoshi" to move around in my 2D game

document.onkeydown = (e) => {
  if (e.keyCode == 37) yoshi.style.left = yoshi.offsetLeft - 5 + "px";
  else if (e.keyCode == 38) yoshi.style.top = yoshi.offsetTop - 5 + "px";
  else if (e.keyCode == 39) yoshi.style.left = yoshi.offsetLeft + 5 + "px";
  else if (e.keyCode == 40) yoshi.style.top = yoshi.offsetTop + 5 + "px";
};
#yoshi {
  position: relative;
  width: 80px;
  height: 80px;
  left: 4px;
  top: 4px;
}
<body>
  <div id="quarto">
    <img src="assents/image/yoshi.png" alt="yoshi" id="yoshi" />
  </div>
</body>

The movements to the right and down are working correctly, but when I press the up or left keys, yoshi continues to move down and right instead

Answer №1

Combining the use of style with offsetTop/offsetLeft can be challenging. If you prefer not to define the initial values of top and left in HTML (inline CSS), consider using getComputedStyle. Alternatively, if inline CSS is acceptable, you can replace getComputedStyle(yoshi) with yoshi.style.

document.onkeydown = (e) => {
  if (e.keyCode == 37) yoshi.style.left = parseInt(getComputedStyle(yoshi).left) - 5 + "px";
  else if (e.keyCode == 38) yoshi.style.top = parseInt(getComputedStyle(yoshi).top) - 5 + "px";
  else if (e.keyCode == 39) yoshi.style.left = parseInt(getComputedStyle(yoshi).left) + 5 + "px";
  else if (e.keyCode == 40) yoshi.style.top = parseInt(getComputedStyle(yoshi).top) + 5 + "px";
};
#yoshi {
  position: relative;
  width: 80px;
  height: 80px;
  left: 4px;
  top: 4px;
}
<body>
  <div id="quarto">
    <img src="assents/image/yoshi.png" alt="yoshi" id="yoshi" />
  </div>
</body>

Answer №2

In addition to the insightful tip shared by @haolt:

Instead of depending on styles to retain position information, it's better to manage position data yourself. Here's an example:

let marioPosition = {top: 0, left: 0};

document.onkeydown = (e) => {
  if (e.keyCode == 37) marioPosition.left += 5;
  else if (e.keyCode == 38) marioPosition.top -= 5;
  else if (e.keyCode == 39) marioPosition.left -= 5;
  else if (e.keyCode == 40) marioPosition.top += 5;

  mario.style.top = marioPosition.top + "px";
  mario.style.left = marioPosition.left + "px";
};

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The server appears to be active, but there is a lack of content rendering when using React, Node

When I attempt to run the code in app.jsx, nothing displays even though the index.html is functioning properly. Code from Server.js: var express = require('express'); server.js page var app = express(); app.use(express.static('public' ...

Shopify module is throwing an error stating that React is not defined

I wanted to create my first Shopify module, but I encountered an error in my application page on the shop while using React. Here is my index.js code: import {Page} from "@shopify/polaris"; import {ResourcePicker} from "@shopify/app-bridge- ...

Is there a way to initiate an Edge animation when an onclick event occurs?

I am interested in incorporating an interactive Adobe Edge animation that activates upon the click of a conventional HTML form button. Could you please guide me on how to achieve this? ...

Streaming data from BigQuery to the front-end using Express

Trying to extract a query from BigQuery and stream it to the frontend has been quite a challenge. In the Node.js environment with Express, one would assume it should look something like this: app.get('/endpoint', (req, res) => { bigQuery.cr ...

Retrieve the number of rows in the table component

I'm in need of getting the row count from a table component that I have built using vuejs. My goal is to display the row count outside of the table component structure. The issue with the code snippet below is that it doesn't show the correct row ...

I'm encountering an issue with my array in JavaScript while using // @ts-check in VS Code. Why am I receiving an error stating that property 'find' does not exist on my array? (typescript 2.7

** update console.log(Array.isArray(primaryNumberFemales)); // true and I export it with: export { primaryNumberFemales, }; ** end update I possess an array (which is indeed a type of object) that is structured in the following manner: const primar ...

Valums file-uploader: Restricting file uploads based on user's credit score

Currently utilizing the amazing file uploader by Valums, which can be found at https://github.com/valums/file-uploader One feature I am looking to incorporate is a limit based on the user's account balance. The initial image upload is free, so users ...

What is the best way to ensure a div element on a printed page has a space between its bottom edge and the physical paper, as well as a space between its top

Within my div element lies a collection of other div elements. These elements contain lengthy text that may span multiple pages. I am attempting to print this text starting 50mm from the top edge of every physical paper, and stopping 20mm before the edge o ...

Display a single video on an HTML page in sequential order

My webpage contains a video tag for playing online videos. Instead of just one, I have utilized two video tags. However, when attempting to play both videos simultaneously, they end up playing at the same time. I am seeking a solution where if I start pla ...

Instant access to an interactive online platform

Is it feasible to create a shortcut from a webpage to my desktop for quick access? For instance, if a dynamic web page has 15 documents and I want to easily create shortcuts to them on my desktop by clicking on each one. I understand this is a brief quest ...

a solution to the focus/blur issue in Firefox's browser bug

I have created the following script to validate if a value entered in an input field already exists in the database. $('#nome_field').blur(function(){ var field_name=$('#nome_field').val(); $.ajax({ url: " ...

Confirming the authenticity of a newly added user input with the help of jQuery

Within my current project, I have implemented validation features for text boxes. When a user clicks on a text box, the border is highlighted. If they click elsewhere without entering any value, the border turns red and an alert pop-up appears. In additio ...

The animation speed of the jQuery hashchange event is set to zero, causing the animation

I'm facing an issue with jQuery where my animation inside a hashchange event is not smooth; it happens instantly when triggered. I'm looking for a way to make the animation smoother. jQuery( document ).ready(function() { jQuery(window).on(&a ...

Simple JavaScript validation for inputting names

Hey there, I'm a beginner in javascript and I am struggling with a simple input validation using else if statements. Every time I run the code, it goes directly to the else condition. Can someone please assist me? <!DOCTYPE html> <html lang=& ...

Spontaneous Lettering using HTML Tags

Have you ever tried using a random letter as an HTML tag? I was experimenting with it and found that even though 'f' isn't a standard tag, it functions similarly to a span tag in some cases. I know this may be a silly question, but I've ...

Utilize the string module from a JavaScript file in your React or Next.js project

Within my project structure, I have a file named "test.js" located in the "/constants" directory. The content of this file is as follows: const test = "test!" export default test In another part of my project, specifically within the "/pages" folder, I w ...

Storing additional data from extra text boxes into your database can be achieved using AJAX or PHP. Would you

A dynamic text box has been created using Jquery/JavaScript, allowing users to click on an "Add More" button to add additional input boxes for entering data. However, a challenge arises when attempting to store this user-generated data in a database. Assi ...

Using jquery to toggle the visibility of input fields

I'm encountering an issue with this straightforward code snippet: $("#additional-room").hide(); var numAdd = 0; $("#add-room").click(function(e) { e.preventDefault(); $("#additional-room").show(""); if (numAdd >= 3) return; numAd ...

Using jQuery to select and animate several elements simultaneously without repeating the animation

Issue Summary (Fiddle): I'm trying to make all elements fade out simultaneously when clicked, but the current code causes the target to trigger three times resulting in three alert() calls. I want them to fade together without using a wrapper element ...

Converting HTML into an object using $compile

I am currently working on calling an HTML template and want to bind the data with Angular. I successfully retrieve the data to bind and the HTML, but when I try to compile it, it returns all the HTML binded as an object. How can I convert it back to plain ...