This code doesn't work anymore,

I don’t know what could be wrong with this code. I think this code was meant for the Legacy editor?

// How much did we move last turn?
var moveSpeed = 5;

var walls = [wall, wall2]; // List the names of ALL the walls in my project.

function keyDown(key) {
// Save our old positon
var oldX = this.x;
var oldY = this.y;

// Try to move the character
if (key === 'RIGHT') {
    this.x = this.x + moveSpeed; // Move 5 pixels to the right
} else if (key === 'UP') {
    this.y = this.y - 5; // Move 5 pixels to the right
} else if (key === 'LEFT') {
    this.x = this.x - moveSpeed; // Move 5 pixels to the right
} else if (key === 'DOWN') {
    this.y = this.y + moveSpeed; // Move 5 pixels to the right
}

// If we hit a wall, move us back.
if (hitWalls(this)) {
    this.x = oldX; 
    this.y = oldY;
}

}

// Pass in an object to see if it hit the wall.
function hitWalls(objectToCheck) {
var hitWall = false;

// Go through all of the walls I have listed. 
for (var i=0; i<walls.length; i++) {
    var wallToCheck = walls[i]; 
    // If I hit the wall, let the person who called the function know.
    if (objectToCheck.hitTest(wallToCheck)) {
        hitWall = true; 
    }
}
return hitWall; 

}

for one thing, i don’t know if “RIGHT”, “UP”, etc. should be all caps. I use all lowercase and it works.
another thing is that the function needs a variable, then a name. for example:
var hitWalls = function(objectToCheck) {}

var hitWalls = function(objectToCheck) 
    // code
};

hitWalls(wall1);

my JS is still pretty rusty but it’s something along these guidelines.

and the comments in the first code block all say “move 5 pixels to the right”, just saying

hope this helps

1 Like

@awc95014 , this wasn’t my code. I don’t know anything about code. Luxapodular wrote it a while ago, I think maybe it’s just meant for the legacy editor. If someone could fix this for me that would be awesome!

To make things more simple, I use this code to move the character:

var speed = 7;

if(isKeyDown(‘left’)) {
this.x -= speed;
}
if(isKeyDown(‘right’)) {
this.x += speed;
}
if(isKeyDown(‘up’)) {
this.y -= speed;
}
if(isKeyDown(‘down’)) {
this.y += speed;
}

My script for it is titled update, so if yours was titled key-press the hit(test) function might not work. Btw I’m not a good coder, but here’s a way I use to get it done faster:
Untitled_ Apr 30, 2020 10_38 AM
Hope it works!

just realixed that oldX and oldY aren’t defined. i cant make the code for you now, but maybe when I got time.

They are defined, here, I just took a screenshot and circled them in red:

ah, never mind then. didn’t see that there.