Moving the HTML object back can be achieved by translating several times on the X axis followed by translating on the Y axis

Before I proceed with my inquiry, please keep in mind the following:

  1. I have no intention of using a game engine.
  2. This game is being created using HTML, CSS, and JavaScript.
  3. The controls are set to three arrow keys, where clicking on one should move in the direction it's pointing.

Question:

After clicking the right arrow key multiple times and then pressing the jump box, the targeted HTML object, master-cube, reverts back to its original position before executing the movejump() function. However, I want the HTML object to move from its current position.

I am aware that the transform property defaults to its initial position, but is there a way to make it run from the current position instead? That is the desired behavior.

Here is the link to the code snippet on repl.it: https://repl.it/@ritzcrackerz201/cake

Below is the code snippet for reference:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <title>cake (singleplayer 2d adventure game)</title>
    <style>
        html {
            margin: none;
        }

        body {
            margin: none;
            width: 100vw;
            height: 100vh;
        }

        .arrowcontrols {
            float: left;
            margin-right: 5px;
            margin-top: 20%;
            margin-bottom: 80%;
        }

        #master-cube {
            background-image: url("mastercubes/master1.png");
            background-size: 100%;
            height: 40px;
            width: 40px;
            transition: all 0.5s;
            position: absolute;
        }
    </style>
</head>

<body>
    <script>
    let xarrowmovement = 0;

  function moveright() {
    xarrowmovement += 80;
    document.getElementById("master-cube").style.transform = `translateX(${xarrowmovement}%)`;
    console.log("Executing function 'moveright()'. Moving a distance of " + xarrowmovement + "%");
  }

  function moveleft() {
    xarrowmovement += -80; 
    document.getElementById("master-cube").style.transform = `translateX(${xarrowmovement}%)`;
    console.log("Executing function 'moveleft()'. Moving a distance of " + xarrowmovement + "%");
  }

  let jumpboxupmovementy = 0;
  function movejump() {
    jumpboxupmovementy += 80;
    document.getElementById("master-cube").style.transform = `translateY(${-jumpboxupmovementy}%)`;
    console.log("Executing function 'movejump()'. Moving a distance of " + jumpboxupmovementy + "%");

        setTimeout(function(){ 
      jumpboxupmovementy -= 80;
      document.getElementById("master-cube").style.transform = `translate(${jumpboxupmovementy}%)`;
    }, 500); 
  }
    </script>
    <div id="master-cube"></div>
    <img src="arrows/leftarrow.png" alt="Left Arrow" height="80vh" width="80vw" onclick="moveleft()" class="arrowcontrols">
    <img src="arrows/middlejumpsquare.png" alt="Jump Square" height="80vh" width="80vw" onclick="movejump()" class="arrowcontrols">
    <img src="arrows/rightarrow.png" alt="Right Arrow" height="80vh" width="80vw" onclick="moveright()" class="arrowcontrols">
    </body>
</html>

Answer №1

By re-assigning the value of the style transform property, you are actually moving the object back because it overwrites the previous translation. To avoid this issue, consider concatenating strings using += instead of = when assigning to style.transform. This allows you to stack transforms and create more complex transformations.

If you want a better solution, you can store the x- and y-offsets generated by your inputs in an object and then use that information to create translations when needed. Here is a basic example:

const nav = document.getElementById('nav');
const movableObject = document.getElementById('movable-object');
const translation = { x: 0, y: 0 };
const translate = () => {
  movableObject.style.transform = `translate(${translation.x}%,${translation.y}%)`;
};

nav.onclick = ({ target }) => {
  if (!target.classList.contains('nav-arrow')) return;
  switch(target.id) {
    case 'up': 
      translation.y -= 80;
      setTimeout(() => { translation.y = 0; translate(); }, 500);
      break;
    case 'left': 
      translation.x -= 80;
      break;    
    case 'right': 
      translation.x += 80;
      break;
  };
  translate();
};
#nav {
  width: 72px;
  display: grid;
  grid-template-areas:
  ". up ."
  "left . right";
}

#up {
  grid-area: up;
}

#left {
  grid-area: left;
}

#right {
  grid-area: right;
}

#movable-object {
  width: 10px;
  height: 10px;
  background: black;
}

.nav-arrow {
  text-align: center;
  border: 1px solid black;
  padding: 8px;
  width: 16px;
  height: 16px;
  font-size: 16px;
  cursor: pointer;
  user-select: none;
}
<div id="nav">
  <span class="nav-arrow" id="up">&#8593;</span>
  <span class="nav-arrow" id="left">&#8592;</span>
  <span class="nav-arrow" id="right">&#8594;</span>
</div>

<div id="movable-object"></div>

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

How to assign a value to a property in node.js using a string as

I attempted to create a function that would allow me to update a specific value of an object by providing the property path: reflectionSet = function(obj, propString, value) { var current = obj; var splitted = propString.split('.'); ...

Eliminate unnecessary white space on your webpage using CSS with the 960.gs grid system

As I work on building my portfolio website from scratch, I came across a CSS framework known as "960.gs". While I have experience with similar tools, this is my first time delving into a pure CSS framework, so I'm feeling a bit out of practice. Here ...

Tips for incorporating MUI into your Redwood JS project

Trying to integrate MUI into Redwood JS has been a challenge for me. I attempted to run the following command in the project directory: yarn add @mui/material Unfortunately, an error message appeared in the console stating: An error Running this command w ...

Guidance on showcasing user details post-login authentication using NodeJS and express

Utilizing Cloud Firestore as the database for my project, I have created frontend components using HTML, CSS, and JS. Currently, I am focused on developing the backend functionalities. Successfully implementing registration functions for both doctors and p ...

Important notice: Warning for stand-alone React 18 page regarding the import of createRoot from "react-dom"

I am in the process of developing a standalone webpage utilizing React 18: <!DOCTYPE html> <html lang="en"> <head> <title>Hello React!</title> <script crossorigin src="https://unpkg.com/react@1 ...

Utilize AngularJS to bind a variable and display an external HTML file without the need to open it in a browser

In my setup, I have two HTML Views - one is for application purposes and the other is for printing. Let's call them Application.html and PrintForm.html, respectively. Here is a snippet from Application.html: <!DOCTYPE html> <html> < ...

Is the height of $(element) equal to the clientHeight of the element?

Do these two elements have identical properties? In my experiments, it seems like they yield the same result. I'm currently working on enhancing my code by utilizing native JavaScript properties... ...

Resolving JavaScript ES6 module names

Forgive me if this is a silly question, but I am having trouble understanding how this particular line of code functions: import React from 'react'; My confusion lies in who and where exactly searches for the name 'react'? For instanc ...

Guide to linking audio to MediaStream using Three.JS AudioContext

I have a MediaStream created from a canvas and I am trying to add audio to it from the Three.js audio stream. After attempting various methods, I found that the most concise solution is shown in the code snippet below. The stream seems to be added success ...

The div layer is positioned above the flash object

I have successfully implemented a method where I position a div over a webpage containing a flash object. This absolutely positioned div has a high z-index and captures click events. The main goal is to trigger the click event on the div when the flash obj ...

Converting data to JSON geometry format for implementation in Three.js

Currently, I am in the process of creating an exporter using Maxscript to convert data into JSON format for use in Three.js. Information on this topic is scarce, but I did come across a helpful resource: https://github.com/mrdoob/three.js/wiki/JSON-Geometr ...

Understanding the distinctions among variables in typescript

Can someone explain the difference in Typescript between "!option" and "option"? It seems like they are not equivalent. const limit = !options.limit || options.limit === NaN ? 0 : options.limit ...

Building a table with Next.js

I need assistance in displaying users and their metadata in a table on my website. Here is the code snippet I have: const apiKey = process.env.CLERK_SECRET_KEY; if (!apiKey) { console.error('API_KEY not found in environment variables'); proc ...

The 502 Bad Gateway error strikes again on Google Drive

I have a website with numerous photos stored on Google Drive. The image tags in my code look like this: <img src="https://googledrive.com/host/<foldId>/A14.jpg"> Unfortunately, many of the photos are not loading and instead showing a 502 Bad ...

in Vue.js, extract the style of an element and apply it to a different element

Currently, I am using VUE.js 2 in my project. Here is my website's DOM structure: <aside :style="{height : height()}" class="col-sm-4 col-md-3 col-lg-3">...</aside> <main class="col-sm-8 col-md-9 col-lg-9" ref="userPanelMainContents" ...

How to implement Thymeleaf's notConnected tag when using Spring Social

After transitioning my JSP views to HTML Thymeleaf views, I encountered a problem. In my old JSP views, I used a social:notConnected tag. However, it seems to have been removed and the only one available is social:connected as shown below. <div id="co ...

The oninput event in IE10 is consistently triggered upon redirection

I have encountered a strange issue with IE10 when redirecting the page on an 'oninput' event, which does not occur with Chrome. I have simplified the code to demonstrate the problem: <html> <head> <script type="text/javascript&g ...

Tags for classes are not appearing or being activated on my website

I recently purchased a template from casethemes () and I am experiencing an issue. Despite using the same tags as their demo site, the classes are not being executed properly and appear broken on my website. Could it be that I am missing some necessary lib ...

When incorporating inline-block styling in dompdf, it may result in added space below the elements

One issue that arises when there are multiple elements with display:inline-block is that these elements can sometimes display with a margin below them after being rendered as a PDF: <div style="background-color:pink;"> <div style="background- ...

UnlawfulAccessError/403 Exploring Ajax with Express and Csurf - tips for utilizing Csurf effectively

Hello everyone! I've been working on this project for a week now, and I'm encountering some difficulties. I'm currently developing a Phaser game and I've set up a scoreboard using node.js. This is my first time using node and I'm ...