vendredi 27 février 2015

Javascript why my if-statement is not working

I'm having trouble getting this if-statement below to properly do what I want it to.


This "Baddie" being mentioned in here is a cartoon which is moving around in a box by pressing the arrowkeys that is 400px width, 300px height.


This is a function that is suppose to prevent him from moving outside this box.



var isBaddieMovable = function(moveLeft, moveTop) {
var movable, newLeft, newTop, max;
console.log("Checking if baddie collided with the content walls");
movable = true;
// Get baddie's new position if moved
newLeft = left + moveLeft*step;
newTop = top + moveTop*step;
console.log("Checking collision at", newLeft, newTop);

// Left wall collide check - check if newLeft outside content
var condition = false;
if(newLeft < 0) {
movable = false;
console.log("Baddie collided with left wall");
}
condition = false;
// Top wall collide check - check if newTop is outside content
if(newTop < 0) {
movable = false;
console.log("Baddie collided with top wall");
}
// Right wall collide check
max = 400;
if(newLeft + baddie.offsetWidth > max) {
movable = false;
console.log("Baddie collided with right wall");
}
// Bottom wall collide check
max = 300;
if(newTop + baddie.offsetHeight > max) {
movable = false;
console.log("Baddie collided with bottom wall");
}

// Return if baddie collided
return movable;
};


I can see in the console that the function is finding out the Baddie collided with the wall, but he's still going through the walls even with the movable = false is set.



Console:
Baddie will step 50 pixels each move
Baddie starts at 0,0
37 was pressed
Checking if baddie collided with the content walls
Checking collision at -50 0
Baddie collided with left wall


Is this enough information to help me out? I'm sorry I dont have the entire site uploaded anywhere.


Edit: As someone mentioned, I have added the function for the movement here:



var moveBaddie = function(moveLeft, moveTop) {

left += moveLeft*step;
top += moveTop*step;

baddie.style.left = left + "px";
baddie.style.top = top + "px";
};

Aucun commentaire:

Enregistrer un commentaire