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

2016/3/6

how to push another object

103200 103200

2016/3/6

#
I am making a soccer game with four players and need to get the ball to move when they touch it. How do I do that? And if I wanted a goalie to move back and forth in front of the goal, how would I do that? Thanks
Super_Hippo Super_Hippo

2016/3/6

#
It will look a bit like this:
Ball ball = (Ball) getOneIntersectingObject(Ball.class)
if (ball != null)
{
    ball.setRotation(getRotation());
    ball.setSpeed(speed*2); //speed is the current moving speed of the player
}
And in the Ball class (useful to import the SmoothMover class and let the Ball be a subclass of it)
private double speed = 0;

public void act()
{
    if (speed > 0)
    {
        move(speed);
        speed *= 0.98; //ball slows down on its own
        if (speed < 0.1) speed = 0;
    }
}

public void setSpeed(double newSpeed)
{
    speed = newSpeed;
}
This is just an idea. It won't work exactly like this. For the goal keeper. Let's say he walks up and down between y=100 and y=200.
private int direction = 1;
public void act()
{
    setLocation(getX(), getY()+direction*2)
    if (getY < 100 || getY > 200) direction *= -1;
}
You need to login to post a reply.