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

2016/6/2

Stop moving when hitting objects

MrPancakes MrPancakes

2016/6/2

#
Hi, I'm programming a game. It is a fake Pokémon. But I seem to have a little problem. My charachter won't stop moving if I hit a tree or house. Could you help me out please?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
    {
        if (Greenfoot.isKeyDown ("up") || Greenfoot.isKeyDown ("w"))
        {
            setLocation(getExactX(), getExactY()-moveSpeed);
            setImage("roodkapjeachter.gif");
            if (isTouching(Tree.class))
            {
                move(0);
            }
        }
        if (Greenfoot.isKeyDown ("down") || Greenfoot.isKeyDown ("s"))
        {
            setLocation(getExactX(), getExactY()+moveSpeed);
            setImage("roodkapjevoor.gif");
            if (isTouching(Tree.class))
            {
                move(0);
            }
        }   
        if (Greenfoot.isKeyDown ("left") || Greenfoot.isKeyDown ("a"))
        {
            setLocation(getExactX()-moveSpeed, getExactY());
            setImage("roodkapjelinks.gif");
            if (isTouching(Tree.class))
            {
                move(0);
            }
        }   
        if (Greenfoot.isKeyDown ("right") || Greenfoot.isKeyDown ("d"))
        {
            setLocation(getExactX()+moveSpeed, getExactY());
            setImage("roodkapjerechts.gif");
            if (isTouching(Tree.class))
            {
                move(0);
            }   
        }
    }
}
SPower SPower

2016/6/2

#
The problem is you're moving your character with the setLocation method, but then after that you're checking for collisions. You need to put the setLocation call inside the if-statement, but you can leave the image changing code outside of it (to still have the effect of changing the orientation of Roodkapje/Red riding hood, even when she can't move).
danpost danpost

2016/6/2

#
The line 'move(0)' does not do a thing. It does not negate any movement code that was previously executed. To negate a movement done with the 'setLocation' statement you need to negate the offset and set the location again. For example, to negate the movement done by line 4, you would use:
1
setLocation(getExactX(), getExactY()+moveSpeed);
This line can replace the 'move(0);' at line 8. The same type of change will need to replace all of the 'move(0);' lines.
MrPancakes MrPancakes

2016/6/4

#
Th Thank you guys
MrPancakes MrPancakes

2016/6/14

#
I fixed with your code danpost. Thank you very much
You need to login to post a reply.