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

2016/7/14

Making Solid Walls

cleeming cleeming

2016/7/14

#
import greenfoot.*;  // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)

/**
 * Write a description of class Person here.
 * 
 * @author (your name) 
 * @version (a version number or a date)
 */
public class Person extends Actor
{
    private GreenfootImage left = new GreenfootImage("guyLeft.png");
    private GreenfootImage right = new GreenfootImage("guyRight.png");
    private GreenfootImage up = new GreenfootImage("guy.png");
    private GreenfootImage down = new GreenfootImage("guyBack.png");
    public int moveAmt;
    int dx = 0, dy = 0; 
    /**
     * Act - do whatever the Person wants to do. This method is called whenever
     * the 'Act' or 'Run' button gets pressed in the environment.
     */
    public void act() 
    {
        moveOnKeyPress();
    }    
    public void moveRight()
    {
        int x = (getX() + 5);
        int y = (getY());
         
        setLocation(x, y);
    }
    public void moveLeft()
    {
        int x = (getX() - 5);
        int y = (getY());
         
        setLocation(x, y);
    }
    public void moveDown()
    {
        int x = (getX());
        int y = (getY() + 5);
         
        setLocation(x, y);
    }
    public void moveUp()
    {
        int x = (getX());
        int y = (getY() - 5);
         
        setLocation(x, y);
    }
    public void moveOnKeyPress()
    {
        if((Greenfoot.isKeyDown("left"))||(Greenfoot.isKeyDown("a")))
        {
            moveLeft();
            setImage(left);
        }
        if((Greenfoot.isKeyDown("right"))||(Greenfoot.isKeyDown("d")))
        {
            moveRight();
            setImage(right);
        }
        if((Greenfoot.isKeyDown("up"))||(Greenfoot.isKeyDown("w")))
        {
            moveUp();
            setImage(up);
        }
        if((Greenfoot.isKeyDown("down"))||(Greenfoot.isKeyDown("s")))
        {
            moveDown();
            setImage(down);
        }  
    }
    
}
I need to make the character unable to walk through the blocks but im unsure how to make it do so
Super_Hippo Super_Hippo

2016/7/14

#
Save the current position, move and if it is touching something it shouldn't be able to walk through, walk back.
public void moveOnKeyPress()
{
    int x = getX(), y = getY();
    
    //what you had in the method
    
    if (isTouching(Wall.class)) //I don't know how you called the class
    {
        setLocation(x, y);
    }
}
You need to login to post a reply.