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

2015/1/30

FOR loop explanation

chamuzi3 chamuzi3

2015/1/30

#
I am wondering if there is anyone who can explain to me what the "for" loop below is doing because am confused.
    public void act() 
    {
        move(4);
    }   

    public void move(int moveAmt)
    {
        // determine direction by keypress checking
        int dx = 0, dy = 0;
        if (Greenfoot.isKeyDown("d")) 
        {dx += 1;}
        if (Greenfoot.isKeyDown("a")) 
        {dx -= 1;}
        if (Greenfoot.isKeyDown("s"))
        {dy += 1;}
        if (Greenfoot.isKeyDown("w")) 
        {dy -= 1;}
        // check for wall on each step of move in both vertical and horizontal directions
        for (int i = 0; i < moveAmt; i++)
        {
            setLocation(getX() + dx, getY());
            if (getOneIntersectingObject(Wall.class) != null) setLocation(getX() - dx, getY());
            setLocation(getX(), getY() + dy);
            if (getOneIntersectingObject(Wall.class) != null) setLocation(getX(), getY() - dy);
        }
    }
danpost danpost

2015/1/30

#
Apparently, it is used to step, pixel by pixel (or, rather, cell by cell), through the entire move distance. The horizontal and vertical movements are also done individually. By doing so, the object actor will stop moving in either direction upon intersecting a Wall object and no backing off is required (although, backing up once could still be added when a Wall object is contacted to prevent any intersection with the Wall object).
You need to login to post a reply.