Skip to content
Browse files

Movement, a Function of Time

  • Loading branch information...
1 parent 45958c9 commit 499e26b4cc0dab9bac66ca34dbde51da56b95d8d @crteal crteal committed Oct 29, 2012
Showing with 51 additions and 27 deletions.
  1. +2 −10 script/keyboard.js
  2. +49 −17 script/player.js
View
12 script/keyboard.js
@@ -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];
});
View
66 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);
}
}
@@ -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.
Something went wrong with that request. Please try again.