Before I proceed with my inquiry, please keep in mind the following:
- I have no intention of using a game engine.
- This game is being created using HTML, CSS, and JavaScript.
- 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>