Hello. I am trying to figure out how to make a bouncing ball but can\'t seem to
ID: 3883609 • Letter: H
Question
Hello. I am trying to figure out how to make a bouncing ball but can't seem to figure it out. It's like the bouncing ball in Breakout. I am coding in Processing.
// Bounce aka pong exercise
// Animate a ball that bounces all the edges of the canvas
// Complete this exercise by adding code where you see "ADD CODE HERE"
// The variables x,y give the center of the ball
float x = 200;
float y = 200;
// The variables dx,dy give the velocity of the ball
float dx, dy;
void setup() {
size(400,400);
// Start the ball moving in a random direction
// with a speed of 4 pixels/frame
float angle = random(TWO_PI);
dx = cos(angle)*4;
dy = sin(angle)*4;
}
void draw() {
background(0); // erase canvas
// draw ball at location x,y
// ADD CODE HERE
// update the position of the ball
// ADD CODE HERE
// check to see if the ball has moved past the edge of the canvas.
// If so, negate the appropriate velocity to make the ball bounce
// ADD CODE HERE
}
Explanation / Answer
import java.awt.*;
import java.util.formatter;
import javax.swing.*;
public class BouncingBallSample extends Jpanel{
private static final int BOX_WIDTH=400;
private static final int BOX_HEIGHT=400;
private float ballRadius=200;
private float ballX=ballRadius+50;
private float ballY=ballRadius+20;
private float ballSpeedX=3;
private float ballSpeedY=2;
private static final int UPDATE-RATE=30;
public BouncingBallSimple{
this.setpreffered(new dimension(BOX_WIDTH,BOX_HEIGHT));
thread gamethread=new thread(){
public void run(){
while(true){
ballX=ballX+ballspeedX;
ballY=ballY=ballspeedY;
if(ballX-ballradius<0){
ballspeedX=-ballspeedX;
ballX=ballRadius;
}elseif(ballX+ballRadius>BOX_WIDTH){
ballspeedX=-ballspeedX;
ballX=BOX_WIDTH-ballradius;
}
if(ballY-ballradius<0)
{
ballspeedY=-ballspeedY;
ballY=ballRadius;
}elseif(ballY+ballRadius>BOX_HEIGHT){
ballY=BOX_HEIGHT-ballRadius;
}
repaint();
try
{
Thread.sleep(1000/UPDATE_RATE){
catch(InterruptedException ex){}
}
}
}
};
public void paintcomponent(Graphics g){
super.paint(component(g)){
g.setcolor(color.BLACK);
g.fillRect(0,0,BOX_WIDTH<BOX_HEIGHT);
g.setcolor(color.BLUE);
g.filloval((int)(ballX-ballradius),(int)(ballY-ballradius),(int)(2*ballradius),(int)(2*ballradius));
public static void main(sring[] args){
javax.swing.swingutilities.invokelater(new Runnable()){
publiv void run(){
jframe frame=new jframe("A BOUNCING BALL");
frame.setDefaultcloseoperation(jframe.EXIT_ON_CLOSE);
frame.setcontentpanel(new BouncingBallsimple());
frame.Pack();
frame.setVisible(true);
}
}
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.