Move an element or div with arrow keys

(Greg) #1

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(, 10),
        y = parseInt(, 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 = x + 'px'; = y + 'px';
}, 1/30);

Just because I like it :blush:


Very cool! (52.2 KB)


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.

(Nick ) #4

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

(Nick ) #5

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: (59.7 KB)

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


(Greg) #6

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

(Nick ) #7

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