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

2014/6/29

Player moves through objects.

Expositoa131 Expositoa131

2014/6/29

#
So I'm trying to make it so that my player can't move through blocks of dirt. It works when the dirt is to his right, but he passes through if it's to his left. Any ideas?
import greenfoot.*;  // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)

/**
 * Write a description of class Player here.
 * 
 * @author (your name) 
 * @version (a version number or a date)
 */
public class Player extends Actor
{
    public int dirtInInventory=0;
    public int playerHeight = getImage().getHeight();
    public int playerWidth = getImage().getWidth();
    /**
     * Act - do whatever the Player wants to do. This method is called whenever
     * the 'Act' or 'Run' button gets pressed in the environment.
     */
    public void act() 
    {
        fall();
        checkDirt();
        move();
        dig();
    }    

    public void fall()
    {
        setLocation(getX(),getY()+4);
    }    

    public void checkDirt()
    {
        Actor dirtDown = getOneIntersectingObject(Dirt.class);
        if(dirtDown!=null){
            setLocation(getX(),getY()-4);
        }
        Actor dirtLeft = getOneObjectAtOffset(0,-25,Dirt.class);
        if(dirtLeft!=null){
            move(3);
        }
        Actor dirtRight = getOneObjectAtOffset(0,25,Dirt.class);
        if(dirtRight!=null){
            move(-3);
        }
    }

    public void move()
    {
        if(Greenfoot.isKeyDown("right"))
        {
            setLocation(getX()+3,getY());
        }
        if(Greenfoot.isKeyDown("left")){
            setLocation(getX()-3,getY());
        }
    }

    public void dig()
    {
        if(Greenfoot.isKeyDown("d")){
            Actor dirtRight2 = getOneObjectAtOffset(25,0,Dirt.class);
            if(dirtRight2!=null)
            {
                getWorld().removeObject(dirtRight2);
                dirtInInventory++;
            }
        }  
        if(Greenfoot.isKeyDown("a")){
            Actor dirtLeft2 = getOneObjectAtOffset(-25,0,Dirt.class);
            if(dirtLeft2!=null)
            {
                getWorld().removeObject(dirtLeft2);
                dirtInInventory++;
            }    
        }
    }}
P.s I'm a total beginner with programming!
danpost danpost

2014/6/29

#
It looks line lines 37 and 41 are checking above and below the actor instead of to the left and right.
Expositoa131 Expositoa131

2014/6/29

#
Oh you're right. Knew it would be something stupid! Cheers.
You need to login to post a reply.