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

2020/3/25

Make Actor Move Left and Right when hitting another Actor

tcbcRyan tcbcRyan

2020/3/25

#
I have my Enemy actor set to move left and when it hit's a certain actor named "invisibleBarrier" it stops. I would like to make it so that it makes the Enemy actor move the other direction and when hitting another actor which I named "invisibleBarrierRight", it changes direction again and repeats that process as a patrol route. I found this code from another user requesting help but it didn't seem to work out how I was hoping. Here is my code:
public void act() 
    {
        patrolArea();
        steps = (steps+1)%300;
    }    

    private void patrolArea()
    {
        if(getObjectsInRange(20, invisibleBarrier.class).isEmpty())
        {
            if (steps == 0) speed = -speed;
            move(speed);
        }
    }
danpost danpost

2020/3/25

#
If you are using two different actors, you will need two different sets of conditions. Also, to move continually, the only move statement cannot be placed under some conditions. Try:
move(speed);
if (speed > 0 && isTouching(InvisibleBarrierRight.class)) speed = -speed;
if (speed < 0 && isTouching(InvisibleBarrier.class)) speed = -speed;
If wanted, you could also adjust the position of the enemy so that it is no longer touching the barrier at that time.
tcbcRyan tcbcRyan

2020/3/25

#
Thank you that worked to make them go back and forth but I am also trying to make their image change to "EnemyRight" when the hit the left wall and start moving right and "EnemyLeft" when the hit the right wall and start moving left. How could I add that in?
danpost danpost

2020/3/25

#
tcbcRyan wrote...
Thank you that worked to make them go back and forth but I am also trying to make their image change to "EnemyRight" when the hit the left wall and start moving right and "EnemyLeft" when the hit the right wall and start moving left. How could I add that in?
By expanding the blocks out:
if (speed > 0 && isTouching(InvisibleBarrierRight.class))
{
    speed = -speed;
    setImage(EnemyLeft);
}
if (speed < 0 && isTouching(InvisibleBarrier.class))
{
    speed = -speed;
    setImage(EnemyRight);
}
tcbcRyan tcbcRyan

4 days ago

#
Thank you that really helped!
You need to login to post a reply.