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

2016/4/20

Create a new Ball when you right-click on an existing Ball

chrisbsports chrisbsports

2016/4/20

#
How do you create a new Ball at a random location when you right-click on an existing Ball. Here is my existing code:
public class Ball extends Actor
{
    private int deltaX;         // x movement speed
    private int deltaY;         // y movement speed
    private int count = 2;
    
    /**
     * Create a ball with random movement.
     */
    public Ball()
    {
        deltaX = Greenfoot.getRandomNumber(11) - 5;
        deltaY = Greenfoot.getRandomNumber(11) - 5;
    }
    
    /**
     * Act. Move and produce smoke.
     */
    public void act() 
    {
        makeSmoke();
        move();
    }
    
    /**
     * Move the ball. Then check whether we've hit a wall.
     */
    public void move()
    {
        setLocation (getX() + deltaX, getY() + deltaY);
        checkWalls();
    }
    
    /**
     * Check whether we've hit one of the walls. Reverse direction if necessary.
     */
    private void checkWalls()
    {
        if (getX() == 0 || getX() == getWorld().getWidth()-1) {
            deltaX = -deltaX;
        }
        if (getY() == 0 || getY() == getWorld().getHeight()-1) {
            deltaY = -deltaY;
        }
    }
    
    /**
     * Put out a puff of smoke (only on every second call).
     */
    private void makeSmoke()
    {
        count--;
        if (count == 0) {
            getWorld().addObject (new Smoke(), getX(), getY());
            count = 2;
        }
    }
}
danpost danpost

2016/4/20

#
Create a method that detects a click on the actor and then creates a ball and adds it into the world at a random location. Then add a call to the method in the act method.
You need to login to post a reply.