This site requires JavaScript, please enable it in your browser!
Greenfoot back
stateoaks
stateoaks wrote ...

2014/1/7

Code for creating a solid object?

stateoaks stateoaks

2014/1/7

#
I'm creating a top down style game and have everything designed- however, none of the walls work. How would I create a solid object that stops a character from moving through it? I've tried several bits of code but I seem to be making a dogs breakfast out of each one while trying to make it work for me. Thanks all, State
Gevater_Tod4711 Gevater_Tod4711

2014/1/7

#
You could try to check whether there is a wall in front of your moving character before he moves into this wall. E.g. when your character moves right you can check whether there is a wall on his right by using the getOneObjectAtOffset method like this:
1
2
3
4
5
6
if (Greenfoot.isKeyDown("right")) {
    //the character wants to move to the right;
    if (getOneObjectAtOffset(15, 0, Wall.class).isEmpty()) {
        //there is no wall so the character can move;
    }
}
Instead of Wall.class you have to use the right classname of the solid object.
stateoaks stateoaks

2014/1/7

#
it's coming up with an error when compiling- " Cannot find symbol - method isEmpty(). I understand what the code you sent does, but I have no idea why it's not working. Thanks
Gevater_Tod4711 Gevater_Tod4711

2014/1/7

#
Oh sorry that was my fail. Instead of .isEmpty you can use != null. Then it should work. The code then should look like this:
1
2
3
4
5
6
if (Greenfoot.isKeyDown("right")) { 
    //the character wants to move to the right; 
    if (getOneObjectAtOffset(15, 0, Wall.class) != null) { 
        //there is no wall so the character can move; 
    
}
stateoaks stateoaks

2014/1/7

#
Heh, funnily enough I figured it out about 10 minutes before you replied. The code is compiling now but I have no idea how to make the character stop moving when it hits the wall. I've tried a few things but can't seem to think of/find anything that works (bit of a greenhorn- no pun intended). Thanks again
stateoaks stateoaks

2014/1/13

#
I have it sorted! It could be refined at some point but for the moment it works. Thanks for all the help :)
SAAEngineer SAAEngineer

2014/5/8

#
It's a very stupid question but in your code there is Wall.class , if i have an object called Side how would i have to rename the .class bit?
Gevater_Tod4711 wrote...
Oh sorry that was my fail. Instead of .isEmpty you can use != null. Then it should work. The code then should look like this:
1
2
3
4
5
6
if (Greenfoot.isKeyDown("right")) { 
    //the character wants to move to the right; 
    if (getOneObjectAtOffset(15, 0, Wall.class) != null) { 
        //there is no wall so the character can move; 
    
}
You need to login to post a reply.