Skip to content
This repository has been archived by the owner on Feb 16, 2018. It is now read-only.

Commit

Permalink
Movement, a Function of Time
Browse files Browse the repository at this point in the history
  • Loading branch information
crteal committed Oct 30, 2012
1 parent 45958c9 commit 499e26b
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 27 deletions.
12 changes: 2 additions & 10 deletions script/keyboard.js
Expand Up @@ -6,19 +6,11 @@ var Keyboard = (function (el) {
return el.addEventListener(e, l, false);
}

function unlisten(el, e, l) {
return el.removeEventListener(e, l, false)
}

function test (e) {
listen(el, "keydown", function (e) {
k[e.keyCode] = true;
unlisten(el, "keydown", test);
}

listen(el, "keydown", test);
});

listen(el, "keyup", function (e) {
listen(el, "keydown", test);
delete k[e.keyCode];
});

Expand Down
66 changes: 49 additions & 17 deletions script/player.js
@@ -1,48 +1,80 @@
var player = (function (s, p) {
var l, speed = s, position = initPosition = p;
var l,
speed = s,
position = (initPosition = p);

function update(dt) {
var last = position, kb = Keyboard(), orientation, velocity;
var sx,
sy,
dx,
dy,
doMove,
orientation,
velocity,
kb = Keyboard(),
last = position.slice(0);

orientation = [(function () {
if (isKeyDown(kb, 37)) {
delete kb[37];
return -1;
} else if (isKeyDown(kb, 39)) {
delete kb[39];
return 1;
}
return 0;
} ()), (function () {
if (isKeyDown(kb, 38)) {
delete kb[38];
return -1;
} else if (isKeyDown(kb, 40)) {
delete kb[40];
return 1;
}
return 0;
} ())];

velocity = orientation.map(function (o) {
return o * speed;
return o * speed * (dt / 1000);
});

position = vect2dAdd(velocity, position);

dx = floor(position[0]);
dy = floor(position[1]);
sx = floor(last[0]);
sy = floor(last[1]);

if (!(inbounds(position[0], position[1]) && !occupied(position[0], position[1]))) {
position = last;
if (dx != sx || dy != sy) {
doMove = true;
}

if (doMove) {
if (!(inbounds(dx, dy) && !occupied(dx, dy))) {
position = last;
} else {
l = last;
}
}
}

function draw() {
var el = elem(".player"), t = tile(position[0], position[1]);
if (t && l && l != position) {
tile(l[0], l[1]).removeChild(el);
}
if (t) {
t.appendChild(el);
l = position;
var st,
hasMoved,
el = elem(".player"),
dx = floor(position[0]),
dy = floor(position[1]),
sx = dx,
sy = dy,
dt = tile(dx, dy);

if (dt) {
if (l) {
sx = floor(l[0]);
sy = floor(l[1]);
}

st = tile(sx, sy);
if (st && st.childNodes.length) {
st.removeChild(el);
}
dt.appendChild(el);
}
}

Expand All @@ -51,4 +83,4 @@ var player = (function (s, p) {
draw: draw
};

} (1, [0, 0]));
} (2, [0, 0]));

0 comments on commit 499e26b

Please sign in to comment.