hi
I am trying to get the ball to bounce off my paddle like in the coding challenge ‘pong’ video. I have followed step by step and the ball is bouncing off random parts of the page and not off my paddle.
can somebody help me plz
import org.gamecontrolplus.gui.*;
import org.gamecontrolplus.*;
import net.java.games.input.*;
ControlIO control;
ControlDevice stick;
Ball ball;
Paddle center;
int score;
String s;
boolean intersect;
float px;
boolean trailOn;
PImage img;
ArrayList<PVector> shadows = new ArrayList<PVector>();
ArrayList<PVector> trail = new ArrayList<PVector>();
public void setup() {
size(1000, 700);
ball = new Ball();
center = new Paddle(true);
img = loadImage("Gun.png");
// Initialise the ControlIO
control = ControlIO.getInstance(this);
// Find a device that matches the configuration file
stick = control.getMatchedDevice("joystick");
if (stick == null) {
println("No suitable device configured");
System.exit(-1); // End the program NOW!
}
// Setup a function to trap events for this button
stick.getButton("SHADOW").plug(this, "dropShadow", ControlIO.ON_RELEASE);
}
// Poll for user input called from the draw() method.
public void getUserInput() {
px = map(stick.getSlider("X").getValue(), -1, 1, 0, width);
//py = map(stick.getSlider("Y").getValue(), -1, 1, 0, height);
trailOn = stick.getButton("TRAIL").pressed();
}
/// Event handler for the SHADOW button
public void dropShadow() {
// Make sure we have the latest position
getUserInput();
shadows.add(new PVector(px, 40));
}
public void draw() {
getUserInput(); // Polling
background(255, 255, 240);
// Draw shadows
for (PVector shadow : shadows)
ellipse(shadow.x, shadow.y, shadow.z, shadow.z);
if (trailOn)
trail.add(new PVector());
else
trail.clear();
if (trail.size() > 1) {
stroke(132, 0, 0);
for (int n = 1; n < trail.size(); n++) {
PVector v0 = trail.get(n-1);
PVector v1 = trail.get(n);
line(v0.x, v0.y, v1.x, v1.y);
v0 = v1;
}
}
ball.checkPaddle(center);
center.update();
center.show();
ball.show();
ball.update();
ball.edges();
}
class Ball {
float x = width/5;
float y = height/15;
float xspeed = 3;
float yspeed = 3;
float r = 12;
Ball(){
}
void checkPaddle(Paddle px){
if (y < px.y + px.h/2 && y > px.y - px.h/2 && x - r < px.x + px.w/2){
// if (x < px.x + px.w/2 && x > px.x - px.x/2 && y - r < px.y + px.h/2){
xspeed *=-1;
}
}
void update(){
x = x + xspeed;
y = y + yspeed;
}
void reset(){
x = random(width);
y = height/15;
}
void edges(){
if (x < 0 ||x > width){
xspeed *=-1;
}
if(y > height){
reset();
}
if (y < 0){
reset();
}
}
void show(){
fill(150);
ellipse (x,y,r*2,r*2);
}
}class Paddle{
float x;
float y = height/2;
float w = 1000;
float h = 1;
float ychange = 0;
void update(){
y+= ychange;
y = constrain(y,h/2, height-h/2);
}
void move(float steps){
ychange = steps;
}
Paddle(boolean center){
if(center){
x = w/2;
} else {
x = width - w;
}
}
void show(){
noStroke();
imageMode(CENTER);
image(img,px,700, 300,300);
//fill(255);
//rectMode(CENTER);
//rect(px, 700, 100, 200);
}
}