EKsumic's Blog

let today = new Beginning();

Click the left button to use the catalog.

OR

[Tutorial] Teach you step by step to use JavaScript to write a Sokoban game (Part 2)

previous: [Tutorial] Teach you step by step to use JavaScript to write a Sokoban game (Part 1)

Okay, we learned the logic of detecting key presses before. This is the most basic but also the most core part. After all, we need to control game characters.

Next, I will use an image to represent the character you control. Let us find any image you like.

Then, our code is:

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>KeyBoardEvent Demo</title>
</head>
<body>
<img id="You" style="position:absolute" src="character.jpg"/>
<script type="text/javascript">
document.onkeydown=function(e){
    var keyNum=window.event ? e.keyCode :e.which;    
    var character=document.getElementById("You");
    if(keyNum==87){
    console.log('You pressed W');
    character.style.top=character.offsetTop-100+"px";
    }
    if(keyNum==83){
    console.log('You pressed S');
    character.style.top=character.offsetTop+100+"px";    
    }
    if(keyNum==65){
    console.log('You pressed A');
    character.style.left=character.offsetLeft-100+"px";
    }
    if(keyNum==68){
    console.log('You pressed D');
    character.style.left=character.offsetLeft+100+"px";
    }
}
</script>
</body>
</html>

The above code means: when you press the "W" key, the offsetTop of the image with id "You" will be reduced by 100 pixels; when you press the "A" key, the image with id "You" The offsetLeft will be reduced by 100 pixels...and so on.

The position must be set to absolute. That means style="position:absolute" is necessary. 

If this is not set, your image will not be controlled by "WSAD" keys.

Here I tried to introduce the above code on my page, you can try to use WSAD to control this image.

star

 

 

Have fun!

 

Next: [Tutorial] Teach you step by step to use JavaScript to write a Sokoban game (Part 3)

This article was last edited at 2020-11-15 22:24:06

* *