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

2015/1/21

Bounce an Object off of walls, but not so easy?

DiplomatikCow DiplomatikCow

2015/1/21

#
My particles move around all the time, following their set direction ( which is a random number ), yet when they reach the edge, and I'm sure this is simple but I just can't figure it out, I want them to seemingly bounce of the walls. I could do it with setLocation method, but I'm trying to make them follow their direction, just using move(). Help????
DiplomatikCow DiplomatikCow

2015/1/21

#
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
Color randomColor = new Color(Greenfoot.getRandomNumber(255), Greenfoot.getRandomNumber(255), Greenfoot.getRandomNumber(255), 255);
    private int Direction = Greenfoot.getRandomNumber(360);
    private int Speed = Greenfoot.getRandomNumber(4)+5;
    private int facing = getRotation();
    public Particle()
    {
        setRotation(Direction);
        GreenfootImage image;
        image = new GreenfootImage(5, 5);
        image.setColor(randomColor);
        image.drawOval(0,0,5,5);
        image.fillOval(0,0,5,5);
        setImage(image);
    }
    public void act()
    {
        movement();
    }   
    public void movement()
    {
        move(Speed);
    }
    public void bounceOff()
    {
        if(isAtEdge())
        {
 
        }
    }
}
danpost danpost

2015/1/21

#
The following would work to have the actors reverse direction upon encountering an edge:
1
2
3
4
5
6
7
public void bounceOff()
{
    if (isAtEdge())
    {
        turn(180);
    }
}
But, that is probably not the behavior you want. To bounce off an edge at an equal and opposite angle (reflective angle), you will need to determine if the edge is a horizontal or a vertical one, then adjust the direction accordingly. Since you will have to check for each edge individually, it makes no sense to call 'isAtEdge' first. Just check each pair and change the rotation if the actor is at one of them:
1
2
3
4
5
public void bounceOff()
{
    if (getX() == 0 || getX() == getWorld().getWidth()-1) turn(-2*getRotation());
    if (getY() == 0 || getY() == getWorld().getHeight()-1) turn(180-2*getRotation());
}
Make sure you call this method after calling 'movement' in the 'act' method.
DiplomatikCow DiplomatikCow

2015/1/21

#
Thanks :)
You need to login to post a reply.