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

2017/5/25

Solid Wall

Kevroa Kevroa

2017/5/25

#
Hi, I need help creating a solid object. I have a crate aswell as a wall that I don't want the character to run through. Ive tried using getOneIntersectingObject aswell as getObjectsAtOffset to create collision but I cant seem to get it to work properly. I would shot the code that I have so far but iI've pretty much deleted everything at this point becuase I was just going deeper and deeper into a hole.
danpost danpost

2017/5/25

#
Will still need to see what you use for movement of the actor and also to know what the three numbers are that you used in the 'super' call to create the world (first line in your world constructor).
Kevroa Kevroa

2017/5/25

#
Movement:
public void act() 
    {
        if (Greenfoot.isKeyDown("W"))
        {
            setLocation(getX(),getY()-2);
        }
        if (Greenfoot.isKeyDown("A"))
        {
            setLocation(getX()-2,getY());
        }
        if (Greenfoot.isKeyDown("S"))
        {
            setLocation(getX(),getY()+2);
        }
        if (Greenfoot.isKeyDown("D"))
        {
            setLocation(getX()+2,getY());
        }
    }
Super:
public Level()
    {    
        super(400, 300, 1); 
        prepare();
    }
danpost danpost

2017/5/25

#
Okay, first thing that needs done is to add variables to hold what movement was done. The character can move either way horizontally and vertically. So, a variable for change along the x-axis and a variable for change along the y-axis are needed. Your act method will now look like this:
public void act()
{
    int dx = 0, dy = 0; 
    if (Greenfoot.isKeyDown("W")) dy = -2;
    if (Greenfoot.isKeyDown("A")) dx = -2;
    if (Greenfoot.isKeyDown("S")) dy = 2;
    if (Greenfoot.isKeyDown("D")) dx = 2;
    setLocation(getX()+dx, getY()+dy);
}
Now, that dx and dy are there, the actor can move backward using another setLocation subtracting the values instead of adding them if it touching either a wall or a crate. After the 'setLocation' line:
if (isTouching(Wall.class) || isTouching(Crate.class))
{
    setLocation(getX()-dx, getY()-dy);
}
You need to login to post a reply.