Move an element or div with arrow keys

Insert a element with an ID named “moveMe”, add the script to “On Scene Load” in the “Scene Inspector”

var p1 = document.getElementById('moveMe'),
keyCodes = { left: 37, up: 38, right: 39, down: 40 },
keys = [];

window.addEventListener('keydown', function (evt) {
    keys[evt.keyCode] = true;
});

window.addEventListener('keyup', function (evt) {
    keys[evt.keyCode] = false;
});

setInterval(function () {
    
    // get position of div
    var x = parseInt(p1.style.left, 10),
        y = parseInt(p1.style.top, 10);
    
    // update position
    // left/right
    if (keys[keyCodes.left]) {
        x -= 1;
    } else if (keys[keyCodes.right]) {
        x += 1;
    }
    // up/down
    if (keys[keyCodes.up]) {
        y -= 1;
    } else if (keys[keyCodes.down]) {
        y += 1;
    }
    
    // set div position
    p1.style.left = x + 'px';
    p1.style.top = y + 'px';
    
}, 1/30);

Just because I like it :blush:

1 Like

Very cool!

movemedemo.zip (52.2 KB)

4 Likes

This looks similar to the technique mentioned here...

The problem is that it doesn't work with Hype/Matter.js physics. If you don't care about that, then @Nick suggested another way... Crafty.JS…Potential Game engine for use in Hype ...I liked how crafty.js makes it easy to move elements and add key based controls.

Update: Oh... this part of the "Function Library" forum.

Awesome!!! I love this!!
A great addition @gasspence! :smile:

1 Like

@gasspence
Greg, and anyone else…
Here is a little template creativity starter to help folks get started with any mods you would like to make to a basic little tank shooter.
Again thank Greg for the great movement script that is the key!! :smile:
tankshoot.hype.zip (59.7 KB)

Ideas: Animate the halftrack, animate the turret.
Create a Reload and the ideal (collision and scoring
Detecting collisions & playing sounds)

Enjoy!
Nick

2 Likes

I really can't take credit for the script, I got it from reddit's r/learnjavacript

1 Like

This one adds a keypress for shooting.
tankshoot 2.hype.zip (64.8 KB)

1 Like