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

2024/11/25

object/entity passes through barrier

soap soap

2024/11/25

#
In my game project I'm trying to make a barrier, where you can't pass through. The player actor doesn't pass and can move without an issue, but the entity actor (which is an object that moves freely without stopping) either passes through the barrier or gets stuck and stops moving. (both actors use the checkObstacle method) How do I fix the code so that the entity changes its moving direction upon collision with the barrier?
public class Human extends BaseClass
{
    private int x;
    private int randomWalk = 3;
    private int speed = 3;
    
    public void act()
    {
        turnAtEdge();
    }
    
    public void turnAtEdge()
    {
        int min=0;
        int max=90;
        int x = getX();
        int y = getY();
        move(4);

        if(atWorldEdge())
        {
            if (getX()>570)
            {
                max=getRandomNumber(150,210);
                setImage("steveleft.png");
                
            }
            else if (getY() > 370) 
            {
                max=getRandomNumber(240,300);
                setImage("steveback.png");
                
            }
            else if (getX() < 30)
            {
                max=getRandomNumber(0,60) - 30;
                setImage("steveright.png");
                
            }
            else if (getY() < 30)
            {
                max=getRandomNumber(60,120);
                setImage("stevefront.png");
                
            }
            setRotation(max);
            checkObstacle(x, y);
        }
        
    }
    public int getRandomNumber(int min, int max)
    {
     Random random = new Random();
     int n = random.nextInt(max-min) + min;
     return n; 
    }
danpost danpost

2024/11/26

#
You are probably letting the entity pass the barrier to begin with -- which should not be allowed to happen. When a collision is encountered, move the actor back to the original (x, y), which should be inside the barriers.
You need to login to post a reply.