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

2013/9/24

Help bouncing balls

Nabulion Nabulion

2013/9/24

#
hey I have some trouble, making the ball bounce, when it hit any of the four walls. its a School project so i have to use the true/false part. I simply cant figure out whats wrong :( please help. my code:
import greenfoot.*;  

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().getHeight()/2 <= 0)  
        {  
            return true;  
        }  
        else  
        {  
            return false;  
        } 
    }

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

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

2013/9/26

#
Figured it out myself :D Just needed to add: if (hitTopWall()){ Vel = Vel.horizontalFlip(); ect.
You need to login to post a reply.