Is it possible to add collision effects to an image in Java, drawn using the drawImage() method ? If so, how could I do it?
Example:
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.event.KeyEvent;
public class Racquet {
private static final int Y = 330;
private static final int WIDTH = 60;
private static final int HEIGHT = 10;
int x = 0;
int xa = 0;
private Game game;
public Racquet(Game game) {
this.game = game;
}
public void move() {
if (x + xa > 0 && x + xa < game.getWidth() - WIDTH)
x = x + xa;
}
public void paint(Graphics2D g) {
g.fillRect(x, Y, WIDTH, HEIGHT);
}
public void keyReleased(KeyEvent e) {
xa = 0;
}
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_LEFT)
xa = -1;
if (e.getKeyCode() == KeyEvent.VK_RIGHT)
xa = 1;
}
public Rectangle getBounds() {
return new Rectangle(x, Y, WIDTH, HEIGHT);
}
public int getTopY() {
return Y;
}
}
Ball class:
import java.awt.Graphics2D;
import java.awt.Rectangle;
public class Ball {
private static final int DIAMETER = 30;
int x = 0;
int y = 0;
int xa = 1;
int ya = 1;
private Game game;
public Ball(Game game) {
this.game= game;
}
void move() {
if (x + xa < 0)
xa = 1;
if (x + xa > game.getWidth() - DIAMETER)
xa = -1;
if (y + ya < 0)
ya = 1;
if (y + ya > game.getHeight() - DIAMETER)
game.gameOver();
if (collision()){
ya = -1;
y = game.racquet.getTopY() - DIAMETER;
}
x = x + xa;
y = y + ya;
}
private boolean collision() {
return game.racquet.getBounds().intersects(getBounds());
}
public void paint(Graphics2D g) {
g.fillOval(x, y, DIAMETER, DIAMETER);
}
public Rectangle getBounds() {
return new Rectangle(x, y, DIAMETER, DIAMETER);
}
}
The above code detects the collision between the racquet and the ball, now, if my racquet/racket was an image, How wuold I be able to detect the collision of it with the ball? Also, are there easier ways for collision detection?(just asking)
class MyImage extends BufferedImage {
int x, y, xa, ya;
public Rectangle getBounds() {
return new Rectangle(x, y, getWidth(), getHeight());
}
// all other methods in raquet remain the same except you remove paint()
private Game game;
public MyImage(Game game) {
this.game = game;
}
public void move() {
if (x + xa > 0 && x + xa < game.getWidth() - WIDTH)
x = x + xa;
}
public void keyReleased(KeyEvent e) {
xa = 0;
}
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_LEFT)
xa = -1;
if (e.getKeyCode() == KeyEvent.VK_RIGHT)
xa = 1;
}
public int getY() {
return y;
}
}
To start an image you read it like this
MyImage myImage=null;
try {
myImage=ImageIO.read(new File(...));
}
catch (Exception ex) { ex.printStackTrace(); }
How wuold I be able to detect the collision of it with the ball?
I see that you already have a getBounds() methods which returns a Rectangle object. You can use this to check for collision.
You can do it like:
if(racquet.getBounds().intersects(ball.getBounds()))
//collision happens
If the ball must be within the racquet, then:
if(racquet.getBounds().contains(ball.getBounds()))
//collision happens
However, if the height of your racquet object includes then length of the racquet handle, you may implement a getHitBox() method for the racquet something like this:
public Rectangle getHitBox(){
return new Rectangle(x, Y, WIDTH, HEIGHT-handleHeight);
}
Is it possible to add collision effects to an image in Java, drawn using the drawImage() method ? If so, how could I do it?
Not sure how your drawImage() was implemented, so I can't comment on that. However, it is definitely possible to add some "collision effects" with custom painting. Whenever a collision is detected, play the animation at specific location (which will be the location where collision occurs).
You may construct a method like:
playAnimation(int locX, int locY, Animation anima, int duration)
In this case Animation class can just play the sprites from a sprite sheet.
Also, are there easier ways for collision detection?(just asking)
You will probably only have 1 ball and at most 4 racquets in your game. In this case, you only need to check whether the ball hits any of the racquets:
for(int x=0; x<allRacquets.size(); x++)
if(allRacquets.get(x).collidesWith(ball))
collidedRacquet = allRacquets.get(x);
CollidesWith() method can be implemented from the collision detection approach mentioned above:
//implement within Racquet class
public boolean collidesWith(Ball ball){
return (this.getBounds().intersects(ball.getBounds()));
}
Related
Hi guys so i have this game made where the user avoids aliens coming from the right side of the screen and then they go past the left side. I need the aliens to reappear from the right side once they leave the left side of the screen. How can i go about doing this?
Here is my existing code:
EDIT:
Added alien class underneath main class
PImage background;
int x=0; //global variable background location
Alien alien1;
Alien alien2;
Alien alien3;
Defender user1;
void setup(){
size(800,400);
background = loadImage("spaceBackground.jpg");
background.resize(width,height);
alien1 = new Alien(800,100,5);
alien2 = new Alien(800,200,5);
alien3 = new Alien(800,300,5);
user1 = new Defender(10,height/2);
}
void draw ()
{
drawBackground();
alien1.move();
alien1.render();
alien2.move();
alien2.render();
alien3.move();
alien3.render();
user1.render();
}
void drawBackground()
{
image(background, x, 0); //draw background twice adjacent
image(background, x+background.width, 0);
x -=4;
if(x == -background.width)
x=0; //wrap background
}
void keyPressed()
{
if(key == CODED) {
if (keyCode == UP) {
user1.y = user1.y - 5;
}
else if (keyCode == DOWN)
{
user1.y = user1.y + 5;
}
}
}
final color Alien1 = color(0,255,0);
final color Alien2 = color(50,100,0);
class Alien
{
int x,y;
int speedX, speedY;
Alien(int x, int y, int speedX)
{
this.x = x;
this.y = y;
this.speedX = speedX;
}
void move()
{
x=x-speedX;
float stepY = random(-5,5);
y = y + (int)stepY;
}
//draw an alien
void render()
{
fill(Alien1);
ellipse(x,y,30,30);
fill(Alien2);
ellipse(x,y,50,15);
}
}
If you upload your Alien class then we can give clearer directions but the idea is that your should add the following logic in your move() method.
void move()
{
x=x-speedX;
float stepY = random(-5,5);
y = y + (int)stepY;
if(this.x < 0) {
this.x = 800; // or width, startingPosition, ...
}
}
Edit: Alien class was added so adapted my solution to the code.
Being new to coding, I watched a video on how to create Pong. That went well, and as a result I wanted to try and recreate Brick Breaker using some of the coding techniques that were used for Pong. So far I have the ball, paddle, and the base of the game. However, the ball does not collide properly with the paddle, instead of bouncing of it passes through.
Code for base game:
import java.applet.Applet;
import java.awt.Color;
import java.awt.Image;
import java.awt.Graphics;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
public class Breaker extends Applet implements Runnable, KeyListener{
final int WIDTH = 600, HEIGHT= 400;
Thread thread;
Graphics gfx;
Image img;
Ball b1;
Player p1;
public void init() {
this.resize(WIDTH, HEIGHT);
this.addKeyListener(this);
b1 = new Ball();
p1 = new Player(1);
img = createImage(WIDTH,HEIGHT);
gfx = img.getGraphics();
thread = new Thread(this);
thread.start();
}
public void paint(Graphics g) {
gfx.setColor(Color.black);
gfx.fillRect(0, 0, WIDTH, HEIGHT);
b1.draw(gfx);
p1.draw(gfx);
g.drawImage(img, 0, 0, this);
}
public void update (Graphics g) {
paint(g);
}
#Override
public void keyPressed(KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_LEFT){
p1.setLeftAccel(true);
}
else if(e.getKeyCode() == KeyEvent.VK_RIGHT){
p1.setRightAccel(true);
}
}
#Override
public void keyReleased(KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_LEFT){
p1.setLeftAccel(false);
}
else if(e.getKeyCode() == KeyEvent.VK_RIGHT){
p1.setRightAccel(false);
}
}
#Override
public void run() {
for(;;) {
p1.move();
b1.move();
b1.checkPlayerCollision(p1);
repaint();
getToolkit().sync();
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
#Override
public void keyTyped(KeyEvent arg0) {
}
}
Ball:
import java.awt.Graphics;
import java.awt.Color;
public class Ball {
int score;
double xVel, yVel, x, y;
public Ball() {
x= 350;
y = 250;
xVel= 0;
yVel = 1;
}
public void draw(Graphics g) {
g.setColor(Color.white);
g.fillOval((int)x - 10, (int)y - 10, 20, 20);
}
public void checkPlayerCollision(Player p1) {
if (x <= 50) {
if(x >= p1.getX() && x <= p1.getX() + 10)
xVel = -xVel;
}
else if (x >= 680) {
xVel = -xVel;
}
}
public void move() {
x += xVel;
y += yVel;
if (y < 10) //Bounce at top side of screen
yVel = -yVel;
if (x < 10) // Bounce at left side of screen
xVel = -xVel;
}
public int getX() {
return (int)x;
}
public int getY() {
return (int)y;
}
}
Player:
import java.awt.Color;
import java.awt.Graphics;
public class Player implements Paddle {
double x, xVel;
boolean leftAccel, rightAccel;
int player, y;
public Player(int player) {
leftAccel = false; rightAccel = false;
x=260; xVel=0;
}
#Override
public void draw(Graphics g) {
g.setColor(Color.white);
g.fillRect((int)x, 380, 80, 10);
}
#Override
public void move() {
if(leftAccel){
xVel -= 2;
}
else if (rightAccel) {
xVel += 2;
}
else if (!leftAccel && !rightAccel) {
xVel = 0;
}
if(xVel >= 5) {
xVel = 5;
}
else if (xVel <= -5) {
xVel = -5;
}
x += xVel;
if(x < 0)
x=0; //Collision with left wall
if(x > 520)
x = 520; //Collision with right wall
}
public void setLeftAccel(boolean input) {
leftAccel = input;
}
public void setRightAccel(boolean input) {
rightAccel = input;
}
#Override
public int getX() {
return (int)x;
}
}
Paddle:
import java.awt.Graphics;
public interface Paddle {
public void draw(Graphics g);
public void move();
public int getX();
}
I don't completely understand hit detection yet, so I just messed with what was used for pong, however, that doesn't work (and I'm sure it might look weird).
Collision detection can be hard to wrap your head around sometimes. What really helps me is to draw on a piece of paper the things I need to check for and write the checks in code one by one. It's also a good idea to keep your axes in mind, it's really easy to mix up an x and a y, but they will have an important effect on gameplay.
My eye was drawn to your checkPlayerCollision function as it seemed a little off, I have changed some checks around and commented what each check/function is doing.
public void checkPlayerCollision(Player p1) {
if (
// Is the ball at or below paddle height?
y <= 50
// AND Is the ball right of the left side of the paddle?
&& x >= p1.getX()
// AND Is the ball left of the right side of the paddle?
&& x <= p1.getX() + 10
) {
// Collision with the paddle!
// (Ball is lower than y=50 and between left and right side of the paddle!)
// As we want the ball to go back up, we will be changing its velocity
// along the Y-axis.
yVel -= yVel;
} else if (x >= 680) {
// This checks whether the ball went too far to the right..?
xVel -= xVel;
}
}
Best tip I can give you: grab a piece of paper and just draw a simple grid or graph and use that to draw out different things you need to check. Be sure to label your (0,0) point so when you work with the different borders, you know which ones are 0 (usually top and left borders) and which ones are equal to width and height of the canvas.
I saw a lot of results on how do move a sprite in Java, but I can't find any that suite my code. I'm following a tutorial on how to make a Pong style game.
You can find the tutorial here. (That's the part I encountered the problem).
Here's my code for the Racquet class:
package com.tennis;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.event.KeyEvent;
public class Racquet {
private static final int Y = 330;
private static final int WIDTH = 60;
private static final int HEIGHT = 10;
int x = 0;
int xa = 0;
private Game game;
public Racquet(Game game) {
this.game = game;
}
public void move() {
if(x + xa > 0 && x + xa < game.getHeight()-60)
x = x + xa;
}
public void paint(Graphics2D g) {
g.fillRect(x, 50, 10, 70);
}
public void keyReleased(KeyEvent e) {
xa = 0;
}
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_UP)
xa = -1;
if(e.getKeyCode() == KeyEvent.VK_DOWN)
xa = 1;
}
public Rectangle getBounds() {
return new Rectangle(x, Y, WIDTH, HEIGHT);
}
public int getTopY() {
return Y;
}
}
Now the part I'm looking at that I need help changing is this:
public void keyReleased(KeyEvent e) {
xa = 0;
}
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_UP)
xa = -1;
if(e.getKeyCode() == KeyEvent.VK_DOWN)
xa = 1;
}
public Rectangle getBounds() {
return new Rectangle(x, Y, WIDTH, HEIGHT);
}
Alrighty, so the actual problem I have is that I need the Racquet to move up and down along the Y axis, at the current moment it's moving along the X axis.
In your move() function replace x = x + xa to:
y = y + xa;
x variable supposed to be y, and pass to the 2nd param for fillRect
public void paint(Graphics2D g) {
g.fillRect(50, x, 10, 70);
}
public abstract void fillRect(int x,
int y,
int width,
int height)
x - the x coordinate of the rectangle to be filled.
y - the y coordinate of the rectangle to be filled.
width - the width of the rectangle to be filled.
height - the height of the rectangle to be filled.
I was overcomplicating things by trying to make the ping pong racquet move on the Y axis instead of the X axis, so I switched it. Problem solved-ish. Now I can finish the game and continue onto making funner Java games.
So I messed around with these integers,
public void paint(Graphics2D g) {
g.fillRect(x, 250, 70, 10);
}
Then I made the keys as so:
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_LEFT)
xa = -1;
if(e.getKeyCode() == KeyEvent.VK_RIGHT)
xa = 1;
}
I really could use some help in order to find a working solution for my game.
My game is almost done, but the walls in my game are still not working as they should.
I have tried to find a solution on the internet for this problem, but i still haven't found a simple way to stop a rectangle just before it will collide with a wall (another rectangle).
Right now i have implemented a collision detection between the player rectangle and the wall rectangle and then stopped it to move, but then it gets stuck inside a wall when it hits.
Want it to stop just before, so it still can move. The code i have done this with so far is here:
Pacman Class
public class Pacman {
private String pacmanup = "pacmanup.png";
private String pacmandown = "pacmandown.png";
private String pacmanleft = "pacmanleft.png";
private String pacmanright = "pacmanright.png";
private int dx;
private int dy;
private int x;
private int y;
private int width;
private int height;
private boolean visible;
private Image imageup;
private Image imagedown;
private Image imageleft;
private Image imageright;
public Pacman() {
ImageIcon i1 = new ImageIcon(this.getClass().getResource(pacmanup));
imageup = i1.getImage();
ImageIcon i2 = new ImageIcon(this.getClass().getResource(pacmandown));
imagedown = i2.getImage();
ImageIcon i3 = new ImageIcon(this.getClass().getResource(pacmanleft));
imageleft = i3.getImage();
ImageIcon i4 = new ImageIcon(this.getClass().getResource(pacmanright));
imageright = i4.getImage();
width = imageup.getWidth(null);
height = imageup.getHeight(null);
visible = true;
x = 270;
y = 189;
}
public int getDx() {
return dx;
}
public void setDx(int dx) {
this.dx = dx;
}
public int getDy() {
return dy;
}
public void setDy(int dy) {
this.dy = dy;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public void setX(int x) {
this.x = x;
}
public void setY(int y) {
this.y = y;
}
public Image getImageup() {
return imageup;
}
public Image getImagedown() {
return imagedown;
}
public Image getImageleft() {
return imageleft;
}
public Image getImageright() {
return imageright;
}
public void setVisible(boolean visible) {
this.visible = visible;
}
public boolean isVisible() {
return visible;
}
public Rectangle getBounds() {
return new Rectangle(x, y, width, height);
}
public void move() {
x += dx;
y += dy;
}
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_LEFT) {
dx = -2;
dy = 0;
}
if (key == KeyEvent.VK_RIGHT) {
dx = 2;
dy = 0;
}
if (key == KeyEvent.VK_UP) {
dx = 0;
dy = -2;
}
if (key == KeyEvent.VK_DOWN) {
dx = 0;
dy = 2;
}
}
Here i have created a Rectangle getBounds method which i use to create an rectangle of the pacman and place an image over it.
Barrier class / Wall class
public class Barrier {
private String barrier = "barrier.png";
private int x;
private int y;
private int width;
private int height;
private boolean visible;
private Image image;
public Barrier(int x, int y) {
ImageIcon ii = new ImageIcon(this.getClass().getResource(barrier));
image = ii.getImage();
width = image.getWidth(null);
height = image.getHeight(null);
visible = true;
this.x = x;
this.y = y;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public boolean isVisible() {
return visible;
}
public void setVisible(Boolean visible) {
this.visible = visible;
}
public Image getImage() {
return image;
}
public Rectangle getBounds() {
return new Rectangle(x, y, width, height);
}
This class also have the Rectangle getBounds class which i use to detect collision.
The last code i show is how i do the collision detection so far:
Code inside Board class
Rectangle r3 = pacman.getBounds();
for (int j = 0; j<barriers.size(); j++) {
Barrier b = (Barrier) barriers.get(j);
Rectangle r4 = b.getBounds();
if (r3.intersects(r4)) {
System.out.println("Wall hit");
pacman.setDx(0);
pacman.setDy(0);
}
}
Well, what i do, if there is a collision between r3 and r4, i gonna set Dx and Dy to 0.. what i want to find another solution so it detect for collision but i wont get stuck inside a wall, but i don't know how to :/
Hope someone will help.
There are two approaches you can follow. One is ugly but easier, the other one requires a deeper redesign of your classes.
1) Ugly/Simple Approach
In the ugly one, you keep moving your guy before doing the collision checks. Simply move your pacman back to the point where it was not stuck. You accomplish that by inverting the last directions used:
Code inside Board class
Change your reaction in case you find a collision: just walk the same distance, backwards.
if (r3.intersects(r4)) {
System.out.println("Wall hit, move back");
pacman.setDx(-pacman.getDx());
pacman.setDy(-pacman.getDy());
// Possibly need to call move() here again.
pacman.move();
break;
}
Ugly, but should work.
Not recommended to coding perfectionists with OCD and heart disease, though.
2) Redesign
In this approach, you test the position pacman will occupy before doing any actual moves. If that spot is not into any barrier, then perform the movement for real.
Code inside Pacman class
Add this method, so that you can check for collisions against the new bounds.
public Rectangle getOffsetBounds() {
return new Rectangle(x + dx, y + dy, width, height);
}
Code inside Board class
// Strip the call to pacman.move() prior to this point.
Rectangle r3 = pacman.getOffsetBounds(); // Check against the candidate position.
for (int j = 0; j<barriers.size(); j++) {
Barrier b = (Barrier) barriers.get(j);
Rectangle r4 = b.getBounds();
if (r3.intersects(r4)) {
System.out.println("Wall hit");
pacman.setDx(0);
pacman.setDy(0);
// Quit the loop. It's pointless to check other barriers once we hit one.
break;
}
}
// Now we're good to move only in case there's no barrier on our way.
pacman.move();
Particularly I prefer this approach, but it's up to you to pick the best one.
This is a grade 12 object oriented programming project.
I have a class called Ball to construct my ball object.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
public class Ball{
private double xPos;
private double yPos;
private int direction;
public Ball(int ixPos, int iyPos, int idirection){
xPos = ixPos;
yPos = iyPos;
direction = idirection;
}
public int returnX(){
return (int)xPos;
}
public int returnY(){
return (int)yPos;
}
public int returnDirection(){
return direction;
}
public void move(){
xPos += 1*Math.cos(Math.toRadians(direction));
yPos -= 1*Math.sin(Math.toRadians(direction));
}
public void collide(int collideWith){
if(collideWith==1){//collide with left wall
if(90<direction && direction<180){
direction = 180-direction;
}
if(180<direction && direction<270){
direction = 540-direction;
}
}
if(collideWith==2){//collide with right wall
if(0<direction && direction<90){
direction = 180-direction;
}
if(270<direction && direction<360){
direction = 540-direction;
}
}
if(collideWith==3){//collide with up wall
if(0<direction && direction<90){
direction = 360-direction;
}
if(90<direction && direction<180){
direction = 360-direction;
}
}
if(collideWith==4){//collide with down wall
direction = 360-direction;
}
}
public void collidePaddle(int collidePos){
if(collidePos!=50 && collidePos!=0){
direction = (50-collidePos)*180/50;
}
}
}
As you can see in the "move" function, right now the ball is going at a very low speed. But i need the ball to go faster. If I change the 1 into something like, 5, there would be a problem. In my main class where it checks if the ball is hitting the wall or blocks to change direction, the ball would go into the wall or the blocks if the amount of pixels the ball can move each time is greater than 1.
To me it seems like there's no way to solve this problem, no idea where I would start thinking, is there a better way of checking collide or something?
Thank you.
Instead of using absolute checks in your collidePaddle check, you should allow for ranges.
For example...
public void collidePaddle(int collidePos){
if (collidePos >= 50) {
direction = (50-collidePos)*180/50;
// Correct the position of the ball to meet the minimum requirements
// of the collision...
} else if (collidePos <= 0) {
direction = (50-collidePos)*180/50;
// Correct the position of the ball to meet the minimum requirements
// of the collision...
}
}
(Sorry, I'm having fun working out your code ;))
This will allow the ball the "pass" beyond the these points within a virtual context, but if you correct the position to componsate, it should make no difference...when it's rendered...
Updated
Here's a REALLY SIMPLE example of what I'm talking about...
public class SimpleBouncyBall {
public static void main(String[] args) {
new SimpleBouncyBall();
}
public SimpleBouncyBall() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception ex) {
}
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new CourtPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class CourtPane extends JPanel {
private Ball ball;
private int speed = 5;
public CourtPane() {
Timer timer = new Timer(40, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
Rectangle bounds = new Rectangle(new Point(0, 0), getSize());
if (ball == null) {
ball = new Ball(bounds);
}
speed = ball.move(speed, bounds);
repaint();
}
});
timer.setRepeats(true);
timer.setCoalesce(true);
timer.start();
}
#Override
public Dimension getPreferredSize() {
return new Dimension(100, 100);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (ball != null) {
Graphics2D g2d = (Graphics2D) g.create();
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
Point p = ball.getPoint();
g2d.translate(p.x, p.y);
ball.paint(g2d);
g2d.dispose();
}
}
}
public class Ball {
private Point p;
private int radius = 12;
public Ball(Rectangle bounds) {
p = new Point();
p.x = 0;
p.y = bounds.y + (bounds.height - radius) / 2;
}
public Point getPoint() {
return p;
}
public int move(int speed, Rectangle bounds) {
p.x += speed;
if (p.x + radius >= (bounds.x + bounds.width)) {
speed *= -1;
p.x = ((bounds.x + bounds.width) - radius) + speed;
} else if (p.x <= bounds.x) {
speed *= -1;
p.x = bounds.x + speed;
}
p.y = bounds.y + (bounds.height - radius) / 2;
return speed;
}
public void paint(Graphics2D g) {
g.setColor(Color.RED);
g.fillOval(0, 0, radius, radius);
}
}
}
My move method doesn't care if you've past the boundaries as it will reposition the ball back to sit within side those boundaries
public int move(int speed, Rectangle bounds) {
// Apply the delta
p.x += speed;
// Have we passed beyond the right side??
if (p.x + radius >= (bounds.x + bounds.width)) {
speed *= -1;
p.x = ((bounds.x + bounds.width) - radius) + speed;
// Have we past beyond the left side??
} else if (p.x <= bounds.x) {
speed *= -1;
p.x = bounds.x + speed;
}
p.y = bounds.y + (bounds.height - radius) / 2;
return speed;
}
Play around with the speed and see what you get ;)