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

2015/1/3

How to make an actor move only when an other actor intersects

sjoerdieman sjoerdieman

2015/1/3

#
I got this piece of code where i make actor A move up and down. I only want this to happen when actor B intersects actor A, there is only one problem when actor B intersects with actor A it removes from the world.
protected void craneMove()
    {
        if(getOneIntersectingObject(CraneStopBottom.class)!= null){
            Counter = 0;
        }
        else if(getOneIntersectingObject(CraneStopTop.class)!= null){
            Counter = 1;
        }

        if(Counter == 0){
            setLocation(getX(), getY()-1);
        }
        else if (Counter == 1){
            setLocation(getX(), getY()+1);
        }
    }
davmac davmac

2015/1/3

#
there is only one problem when actor B intersects with actor A it removes from the world.
If you don't want it remove the actor from the world, you need to remove the code which does so. The code you've posted doesn't remove anything from the world and so presumably isn't the problem. It's also unclear what class that code comes from. Is CraneStopBottom "class A" and CraneStopTop "class B" or vice versa? In other words: can you explain the problem more thoroughly (perhaps avoid using "A" and "B" and just use the real names of the classes, for a start).
danpost danpost

2015/1/3

#
Also 'Counter' for a field name has multiple downsides. First one thing, by convention, field names should begin with a lowercase letter. For another, the name does not remotely describe what the field is for -- you are not using it as a counter, but more as a direction indicator. Better would be to use it for the direction itself, which can be found at the end of lines 11 and 14 -- '-1' and '1':
if (isTouching(CraneStopBottom.class)) {
    direction = -1;
}
else if (isTouching(CraneStopTop.class)) {
    direction = 1;
}
setLocation(getX(), getY()+direction);
You will need to set the field to one of the two values when the object is created (or ensure that the object is added to the world touching an object of one of the two 'stop' classes.
You need to login to post a reply.