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

2014/7/15

Gradually decrease and increasing speed

alexpg95 alexpg95

2014/7/15

#
Hi, I'm a new greenfoot user. This class creates a target that goes up, and then goes down after it reaches a random y-location. How can I have the instantiation of the class decelerate as it goes up, and the accelerate as it goes down?
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
import greenfoot.*; 
 
public class Target extends Actor
{
    private int stopLocation;
    private boolean hasStop;
 
    public Target()
    {
        stopLocation = Greenfoot.getRandomNumber(200);
        hasStop = false;
    }
     
    public void act()
    {
        if(hasStop)  setLocation(getX(), getY() + 1); //moveup
 
        if(getY() == (stopLocation + 100)) {  //the object stops at (stopLocation + 100)
            setLocation(getX(), getY()); //stop
            hasStop = true;
        }
         
        if(!hasStop) setLocation(getX(), getY() - 1); //moves up
 
        if (getY() == 399) {  //if it reaches the bottom again, game over.
            ((CannonWorld) getWorld()).gameOver();
        }
    }
danpost danpost

2014/7/15

#
You want your target to rise and fall as if gravity was influencing it. Gravity is a force that is constantly being applied to an object that creates a constant acceleration to the object in a downward direction (as long as it is not impeded). Acceleration is the change in speed with respect to time (the unit of time in Greenfoot is one act cycle). Normally, a field would track the speed and the acceleration would be added to it in the act method while setting the new location of the object using the speed for the change in the y-coordinate as in the following:
1
2
3
4
5
6
7
8
private int speed = -24; // negative value for going up
 
public void act()
{
    speed++; // apply acceleration to speed
    setLocation(getX(), getY()+speed); // move new speed
    if (getY() == 399) ((CannonWorld)getWorld()).gameOver();
}
This will cause a rise of about 300 pixels, which is the maximum of what you are looking for; but, unfortunately, this will also complete its rise and fall in less than one second at normal scenario speeds, which if probably too fast for what you are looking for. To slow the movement down without slowing down the normal running speed of the scenario, you will have to use 'double' values for speed and add a double field for the acceleration whose value will have to be determined during run-time using maths. See what you can work out and post back if you have problems.
alexpg95 alexpg95

2014/7/16

#
It worked. Thank you so much!!
You need to login to post a reply.