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

I am puzzled as to why my jQuery height and width functions are returning NaN as the result

I am attempting to calculate the ratio of height and width for each image on a webpage. Unfortunately, I am consistently receiving a NaN result and I cannot figure out why. I have been using get() and find() <div class='image-wrapper'> ...

Support for Vue 3.4 same-name shorthand has been added to VS Code

After upgrading my Vue 3 project to version 3.4, I encountered an issue with vs-code highlighting same-name shorthand as an error, even though it was functioning correctly in my code. I am using the volar extension. Is there a way to resolve this so that v ...

unable to retrieve value from JSON object

It appears that I'm having trouble accessing my object variables, most likely due to a silly mistake on my part. When I console.log my array of objects (pResult), they all look very similar with the first object expanded: [Object, Object, Object, Obj ...

Steps for wrapping a class with a higher order component

Is it feasible to encapsulate a class component within a higher order component (HOC) that is also a class? import React, { Component } from "react"; import { View } from "react-native"; import { Toast } from "react-native-easy-toast"; const withToast = ...

CoffeeScript equivalent of when the document is loaded

Recently, I've been delving into Coffeescript for my web application, but I'm encountering a frustrating issue. The methods are not being called until I manually reload the page. I suspect that the missing piece may be the $(document).ready(func ...

SyntaxError: Unexpected '<' symbol found in JavaScript file while attempting to import it into an HTML document

This issue is really frustrating me In my public directory, there is an index.html file Previously, I had a newRelic script embedded within the HTML in script tags which was functioning properly Recently, I moved the script to a separate JavaScript file ...

Guide on incorporating file uploads in an Angular 6 project

I am currently working on creating a component where I have implemented a file upload function in a child component and am attempting to use that component's selector in another one. Here is my project structure: - upload : upload.component.html up ...

Tips for creating a partial matching filter on an array using elements from a separate array

My goal is to filter an array by finding partial matches from another array. To illustrate, consider the following arrays: Array1 = categories: 292300, categories: 300, categories: 292500280 Array2 = 300, 498 After filtering, ...

Utilizing JSDoc annotations for type safety in VSCode with ESLint configuration for TypeScript declarations import

Is there a way to configure VSCode to perform syntax checking on .eslintrc.js and provide autocomplete functionality? I have managed to set up a structure for a JavaScript configuration file with a custom syntax for my application, but the same approach do ...

Prevent AJAX request while in progress?

I've made some adjustments to a jQuery Autocomplete plugin, which now retrieves a JSON object from a MySQL database instead of an array. However, I've noticed that each time I click on the input field, it triggers a new request, even if it&apos ...

Ensuring that all routes in Express 4 redirect from HTTP to HTTPS

Is there a way to redirect all http:// requests to https:// for every route in my express 4 application? I've tried this method, but it seems to cause a redirect loop error I'm currently utilizing the Express 4 Router in the following manner: ...

Ways to alter the CSS class of individual labels depending on the content of textContent

In my HTML template, I'm using jinja tags to dynamically create labels from a JSON object. The loop responsible for generating this content is detailed below. <div class="card mb-0"> {% for turn in response %} <div class="card-he ...

Unable to assign a scroll event delegation by using the "on" method

When attempting to delegate a scroll event in order for my element to maintain the same handler after being returned by an ajax call, I utilized the on method for delegation. $('body').on({ scroll:function(){ alert('scrolling&ap ...

Receiving an 'undefined' result in an asynchronous response even with 'await' and 'then' statements implemented

I'm struggling with sending a GET request, parsing the response, and passing it to another function. It seems like I'm having difficulty dealing with the asynchronous nature of the response. I prefer to stick to using Node.js' built-in modu ...

What is the best way to activate a JavaScript function once a page has finished loading?

Hey there! I have a webpage with 2 text input fields and a DIV element. The first input field is for user input, while the second one is readonly. When the user hits Enter in the first input field, a new page loads into the DIV based on the query result f ...

Challenging glitch in the JavaScript code

My jQuery code seems to be functioning properly in online text editors like Fiddle and StackOverflow snippets. However, when I try to implement the same code in Brackets or view it on GitHub, the navbar scroll down animation fails to work as expected. You ...

What is the best way to update an array in TypeScript when the elements are of different types and the secondary array has a different type as

const usersData = [ { "id": 0, "name": "ABC" }, { "id": 1, "name": "XYZ" } ]; let dataList = []; // How can I transfer the data from the user array to the dataList array? // If I use the map function, do I need to initialize empty values for oth ...

Spring load without CSS

Upon successful login, I am redirected to my main site using the following controller: //Login Success @GetMapping("/login-success") public ModelAndView loginSuccess() { return new ModelAndView("/cont/home.html"); } The URL for this redirection i ...

Troubleshooting multiple file upload errors in Asp.net Mvc using ajax

I am attempting to implement multiple file upload in MVC using jQuery ajax but I am encountering some issues. Here is my HTML design and code: <div id="fileinputdiv"> <input type="file" name="mainfile" id="mainfile" onchange="OnValueChanged(th ...

What methods can be used to crop and style images in a similar manner using html and css?

Is there a way to replicate this specific method? I attempted to achieve the same look by using CSS masking, but the results weren't pleasing. Does anyone have suggestions on how to accomplish this using HTML/CSS? ...