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

2013/9/16

Bouncing Balls help

stef stef

2013/9/16

#
Hi I've some trouble making the balls bounce, when they hit the four walls. My code has been posted below.
import greenfoot.*;  // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)

/**
 * Write a description of class Ball here.
 * 
 * @author (your name) 
 * @version (a version number or a date)
 */
public class Ball extends Actor
{
    
    private Vector Vel;
    
   
    public Ball(int xVel, int yVel)
    {
        Vel = new Vector(xVel, yVel); 
        
    }

    public void act() 
    {
        handleWallCollision();
        move();
    }    

    public void move()
    {
        int x = getX() + Vel.getX();
        int y = getY() + Vel.getY();
        setLocation(x, y);
    }

    public boolean hitTopWall()
    {
        if(getY()+getImage().getHeight()/2 > 0)
        {
            return true;
        }
        else
        {
            return false;
        }
    }

    public boolean hitBottomWall()
    {
        if(getY()+getImage().getHeight()/2 < getWorld().getHeight()-1)
        {
            return true;
        }
        else
        {
            return false;
        }
    }

    public boolean hitLeftWall()
    {
        if(getX()+getImage().getWidth()/2 < 0)
        {
            return true;
        }
        else
        {
            return false;
        }
    }

    public boolean hitRightWall()
    {
        if(getX()+getImage().getWidth()/2 > getWorld().getWidth()-1)
        {
            return true;
        }
        else
        {
            return false;
        }
    }

    public  void handleWallCollision()
    {
        if(hitRightWall())
        {
            Vel.horizontalFlip();
        }
        else if(hitLeftWall())
        {   
            Vel.horizontalFlip();
        }
        else if(hitBottomWall())
        {
            Vel.verticalFlip();
        }
        else if(hitTopWall())
        {
            Vel.verticalFlip();
        }

    }
}
danpost danpost

2013/9/16

#
Of the four wall checks, you will have to add half the height of your actor in two of them and subtract in the other two (you are adding in all four). Also, all your conditions are the reverse of what they should be (for example: change '<' to ">=', etc.). Actually, you should be fine changing them all to '=' (unless your world is unbounded). You may (depending on your results) have to do a double condition when checking for bounce. That is, for an example of top wall check:
if (hitTopWall() && Vel.getY() < 0) Vel.verticalFlip();
stef stef

2013/9/16

#
Thanks! I'll give it a try.
You need to login to post a reply.