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

2013/2/25

Bouncing balls at corresponding angles

Phytrix Phytrix

2013/2/25

#
Hey. I was looking around trying to find a way to bounce a ball off the wall at the opposite angle that it came (so for example, if a ball was travelling at 30 degrees from left to right, I'd want it to bounce off at 150 degrees - if it came at 45 degrees from left to right, I'd want it to bounce off at 135 degrees). Any ideas on how to do this? Regards, Phytrix.
BradM313 BradM313

2013/2/25

#
Maybe this will help? I used it for the game "Bricks"
import greenfoot.*;
 
/**
 * the class Ball represents one ball
 */
public class Ball extends Actor {
 
    private int ballSize;
    private int gameHeight;
    private int gameWidth;
    private int motionX;
    private int motionY;
 
    public Ball() {
        
        this.ballSize = 13;
        this.gameWidth = BrickWorld.getGameWidth();
        this.gameHeight = BrickWorld.getGameHeight();
 
        //behavior
        this.motionX = 5;
        this.motionY = 19;
    }
 
    public void act() {
        moveBall();
    }
 
    public void moveBall() {
 
        int xPosition = this.getX();
        int yPosition = this.getY();
 
        int newX = xPosition + motionX;
        int newY = yPosition + motionY;
 
        //Xas
        if (newX < 0 + ballSize || newX > this.gameWidth - ballSize) {
            motionX = -motionX;
        }
 
        //Yas
        if (newY < + ballSize || newY > this.gameHeight - ballSize) {
            motionY = -motionY;
        }
 
        setLocation(newX, newY);
    }
   
}
BradM313 BradM313

2013/2/25

#
With this is the world:
/**
   * returns the game width
   * @return int
   */
  public static int getGameWidth() {
     return gameWidth;    
  }
   /**
   * returns the game height
   * @return int
   */
  public static int getGameHeight() {
     return gameHeight;    
  }
Phytrix Phytrix

2013/2/26

#
Great. Thanks.
You need to login to post a reply.