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

2020/8/10

Stopping Objects

Vernz Vernz

2020/8/10

#
Hi guys,, I have just started leaning Greenfoot. I wanna make an object which I am controlling (using keys) to stop(moving) when it touches another object(wall) but still can be able to move to any free direction (or backwards). (The same concept when you move an object and it reaches the edge of the world. Still can move backwards and sideways but not forward) I have used an if statement but got stucked looking for a method to use.. Need some help from you.. thanks in advance
danpost danpost

2020/8/10

#
What kind of object? More importantly, what key controls are implemented? Show class codes of controlled object.
RcCookie RcCookie

2020/8/10

#
I think this should work in any way:
//Overrides act method in the object you want to move
public void move(int distance){
    super.move(distance);//move the object normally

    //moves the object back as long as it intersects something, but never further than to the point where it started moving
    for(int i=0; i<distance && (getOneIntersectingObject(Wall.class)!=null || isAtEdge()); i++){
        if(distance > 0){
            super.move(-1);
        }
        else{
            super.move(1);
        }
    }
}
RcCookie RcCookie

2020/8/10

#
I was assuming that you wall class is called „Wall“. Otherwise you have to change line 6.
You need to login to post a reply.