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

2015/9/13

How can I prevent an object from moving if there is an object in front of it?

Stalfoes Stalfoes

2015/9/13

#
I am a total newbie when it comes to Greenfoot. Taking a class in high school and I am absolutely loving it. How is it possible, say if my character is facing a wall (cells are 60pixels squared), how can I prevent him from moving into the wall when I press a button (up) to move forward? I need lots of help as I really don't know much when it comes to Java. If you help please try to tell me virtually every detail on what I need to do when I am implementing your help. Here is what I have so far, and it's not working the right way:
1
2
3
4
5
6
7
8
if (Greenfoot.isKeyDown("up"))
        {
            if (getOneObjectAtOffset(0, 1, Wall.class) != null)
            {
                setRotation(270);
                move(1);
            }
        }
When I play my game, my character can't move up at all. They can move left, right etc. because I haven't made this code for those parts yet. Please help! Thanks for taking the time to read this!
Super_Hippo Super_Hippo

2015/9/13

#
What you code does: If you press the up key -- if there is a wall one square below (!) ---- move up one square That doesn't really make sense. An easy way to do it can be the following. The character moves and then checks if it is touching a wall. If it does, it moves back to the location it was before.
1
2
3
4
5
6
7
int dx=0, dy=0;
if (Greenfoot.isKeyDown("right") dx++;
if (Greenfoot.isKeyDown("left") dx--;
if (Greenfoot.isKeyDown("up") dy--;
if (Greenfoot.isKeyDown("down") dy++;
setLocation(getX()+dx, getY()+dy);
if (isTouching(Wall.class)) setLocation(getX()-dx, getY()-dy);
Stalfoes Stalfoes

2015/9/14

#
Oh, thanks! But the comment took so long to be validated, I already figured it out. Lol. Thank you anyways!
You need to login to post a reply.