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

2020/5/26

Background colour collision detection help

-----Sam----- -----Sam-----

2020/5/26

#
Hello there, i am trying to make a maze game where the character is blocked by the wall. I would like to create a method of stopping the character from moving if it is touching the black pixels on the background of the maze image opposed to creating each wall by hand. I am new to programming and not entirely sure what to do here.
import greenfoot.*;
public class MyWorld extends World
{
    public MyWorld()
    {    
        super(700, 700, 1);
         int x = Greenfoot.getRandomNumber(900);
         int y = Greenfoot.getRandomNumber(600);
         addObject(new Corgi(), 320, 10);
    }
    
}
import greenfoot.*;
public class Corgi extends Animal
{
    public void act() 
    {
        if (Greenfoot.isKeyDown("w"))
        {
            setDirection(NORTH);
            move (4);
        }
        if (Greenfoot.isKeyDown("d"))
        {
            setDirection(EAST);
            move (4);
        }
        if (Greenfoot.isKeyDown("s"))
        {
            setDirection(SOUTH);
            move (4);
        }
        if (Greenfoot.isKeyDown("a"))
        {
            setDirection(WEST);
            move (4);
        }
    }
    
    public static final int NORTH = -1;
    public static final int EAST = 0; 
    public static final int SOUTH = 1;
    public static final int WEST = 2;
    public int direction;   
      
    public void setDirection(int direction)
    {
        this.direction = direction; 
         {
            setRotation(90*direction); 
        } 
    }
}  
Imgur link to maze background I have made the character be able to move freely but i cannot figure out how to stop it from moving. Any help will be greatly appreciated. Thank you :)
danpost danpost

2020/5/26

#
It would probably help to first get the x and y offsets for the direction moving/facing:
int dx = (1-direction)%2;
int dy = direction%2;
Now you can get the world background and compare the color at (getX()+dx*getImage().getWidth()/2, getY()+dy*getImage().getHeight()/2) to Color.BLACK. The color checking will need to be done for each case of moving direction.
You need to login to post a reply.