recalibrate ball in pong so the edge hits first, not the centre in Processing - processing

I've recently built a game of pong for a UNI assignment in Processing, but whenever the ball hits the top, bottom, side of the screen or the 'paddle' it only bounces back once half the ball is off the screen. I just want the edge of the ball to hit first rather than the centre, but am unsure where my code is going wrong. I hope this makes sense, I'm a definite beginner.
Here is my code for reference
//underwater pong
float x, y, speedX, speedY;
float diam = 10;
float rectSize = 200;
float diamHit;
PImage bg;
PImage img;
int z;
void setup() {
size(920, 500);
smooth();
fill(255);
stroke(255);
imageMode(CENTER);
bg = loadImage("underthesea.jpg");
img = loadImage("plastic.png");
reset();
}
void reset() {
x = width/2;
y = height/2;
//allows plastic to bounce
speedX = random(5, 5);
speedY = random(5, 5);
}
void draw() {
background(bg);
image(img, x/2, y);
rect(0, 0, 20, height);
rect(width/2, mouseY-rectSize/2, 50, rectSize);
//allows plastic to bounce
x += speedX;
y += speedY;
// if plastic hits movable bar, invert X direction
if ( x > width-30 && x < width -20 && y > mouseY-rectSize/2 && y < mouseY+rectSize/2 ) {
speedX = speedX * -1;
}
// if plastic hits wall, change direction of X
if (x < 25) {
speedX *= -1.1;
speedY *= 1.1;
x += speedX;
}
// if plastic hits up or down, change direction of Y
if ( y > height || y < 0 ) {
speedY *= -1;
}
}
void mousePressed() {
reset();
}

I wasn't able to run your code because I am missing the background and plastic images, but here's what's probably going wrong. I'm not 100% since I do not know the dimensions of your images either.
You are using imageMode(CENTER). See the documentation for details.
From the docs:
imageMode(CENTER) interprets the second and third parameters of image() as the image's center point. If two additional parameters are specified, they are used to set the image's width and height.
This treats the coordinates you input into the image function as the center of the image.
Your first issue is that you are placing your image at x/2 but doing all your collision checks with x in mind. x does not represent the middle of your image, because you're drawing it at x/2.
Then I'm not sure if you are doing your horizontal collision checks right, as you are checking against hardcoded values. I do know you are doing your vertical collision checks wrong. You are checking if the center of the image is at the top of the canvas, 0, or the bottom of the canvas, height. This means that your image will already have moved out of the screen halfway.
If you want to treat the image coordinates as the center of your image, you need to check the left edge of the image at x - imageWidth / 2, the right edge at X+ imageWidth / 2, the top edge at y - imageWidth / 2 (remember the y coordinates are 0 at the top of the canvas and increase towards the bottom) and the bottom at y - imageWidth / 2. Here's a great website which goes into more detail on 2d collision detection, i'd highly recommend you give it a read. It's an awesome website.

Related

Processing | How to stop the ball from changing it's color

Here's a little code that I've written to get a ball bouncing in Processing. The ball should change it's color everything it bounces off the "ground" and become slower and slower and lay at the ground at the end.
But - and that's the problem I've got - the ball doesn't stops changing it's color at the bottom - and that means it didn't stops bouncing, right?
The question is: How do I tell the ball to stop and not to change it's color anymore?
float y = 0.0;
float speed = 0;
float efficiency = 0.9;
float gravitation = 1.3;
void setup(){
size(400, 700);
//makes everything smoother
frameRate(60);
//color of the ball at the beginning
fill(255);
}
void draw() {
// declare background here to get rid of thousands of copies of the ball
background(0);
//set speed of the ball
speed = speed + gravitation;
y = y + speed;
//bouce off the edges
if (y > (height-25)){
//reverse the speed
speed = speed * (-1 * efficiency);
//change the color everytime it bounces off the ground
fill(random(255), random(255), random(255));
}
//rescue ball from the ground
if (y >= (height-25)){
y = (height-25);
}
/*
// stop ball on the ground when veloctiy is super low
if(speed < 0.1){
speed = -0.1;
}
*/
// draw the ball
stroke(0);
ellipse(200, y, 50, 50);
}
The problem is that even though you are setting the speed to -0.1 when it is small, and y to height - 25, the very next pass through the loop adds gravity to speed and then speed to y, making y larger than height - 25 (by slightly more than 1 pixel) again. This makes the ball jump up and down through an infinite loop of hops of zero height.
You could use a threshold on the reflected speed. If it is below the threshold, stop the loop.
At the top of the file, add a line like
float threshold = 0.5; //experiment with this
Then in draw(), right after the line
speed = speed * (-1 * efficiency);
add the line
if(abs(speed) < threshold) noLoop();
In this case, you can throw away the if clause which checks when the speed is super-low.

Making an object bounce of an other object that is moved by mouseY/mouseX in processing

I am pretty new with processing and need some help. I'm trying to build a simple kickball game. Easy idea: when the ball hits the yellow bar, the ball bounces of. To keep the ball "alive" you have to make it bounce of the yellow bar. I've successfully found code for the bouncing ball (it now bounces of the bottom of the window), and I've also successfully created a bar that moves with the mouse. What I haven't been able to create so far is for the ball to actually bounce of the bar. Looking for som help here!! Thanks!!
float ballX = 100;
float ballY = 0;
float h = 50;
int x, y;
//create a variable for speed
float speedY = 2;
void setup() {
size(400,400);
smooth();
noStroke();
// change the mode we draw circles so they are
// aligned in the top left
ellipseMode(CORNER);
}
void draw() {
//clear the background and set the fill colour
background(0);
fill(255);
//draw the circle in it's current position
ellipse(ballX, ballY, h,h);
//add a little gravity to the speed
speedY = speedY + 0.5;
//add speed to the ball's
ballY = ballY + speedY;
//bar
x = mouseX;
y = mouseY;
fill(255, 255, 0);
rect(x, y, 50, 10);
if (ballY > height - h) {
// set the position to be on the floor
ballY = height - h;
// and make the y speed 90% of what it was,
// but in the opposite direction
speedY = speedY * -0.9;
//switch the direction
//speedY = speedY;
}
else if (ballY <= 0) {
// if the ball hits the top,
// make it bounce off
speedY = -speedY;
}
}
I'd warn you against just copy-pasting code you found on the internet. You have to really understand what it's doing, otherwise you're going to have a ton of headaches as your code becomes more complicated. Try to rewrite the logic yourself, that way you understand exactly how the bouncing works.
To figure out whether the ball is intersecting the paddle, I'd recommend taking out a piece of paper and a pencil and drawing some examples. Try to figure out a pattern of what the position and size of the ball and paddle are when they're intersecting.
But basically, you need to check whether the ball is "inside" the bounds of the rectangle. This is true if the ball is to the right of the left side of the paddle, to the left of the right side of the paddle, below the top of the paddle, and above the bottom of the paddle.

Calculate ellipse size in relation to distance from center point

I want to achieve a slow fade in size on every collapse into itself. In other words, when the circle is at its biggest, the ellipses will be at the largest in size and conversely the opposite for the retraction. So far I am trying to achieve this affect by remapping the cSize from the distance of the center point, but somewhere along the way something is going wrong. At the moment I am getting a slow transition from small to large in ellipse size, but the inner ellipses are noticeably larger. I want an equal distribution of size amongst all ellipses in relation to center point distance.
I've simplified the code down to 4 ellipses rather than an array of rows of ellipses in order to hopefully simplify this example. This is done in the for (int x = -50; x <= 50; x+=100).
I've seen one or two examples that slightly does what I want, but is more or less static. This example is kind of similar because the ellipse size gets smaller or larger in relation to the mouse position
Distance2D
Here is an additional diagram of the grid of ellipses I am trying to create, In addition, I am trying to scale that "square grid" of ellipses by a center point.
Multiple ellipses + Scale by center
Any pointers?
float cSize;
float shrinkOrGrow;
void setup() {
size(640, 640);
noStroke();
smooth();
fill(255);
}
void draw() {
background(#202020);
translate(width/2, height/2);
if (cSize > 10) {
shrinkOrGrow = 0;
} else if (cSize < 1 ) {
shrinkOrGrow = 1;
}
if (shrinkOrGrow == 1) {
cSize += .1;
} else if (shrinkOrGrow == 0) {
cSize -= .1;
}
for (int x = -50; x <= 50; x+=100) {
for (int y = -50; y <= 50; y+=100) {
float d = dist(x, y, 0, 0);
float fromCenter = map(cSize, 0, d, 1, 10);
pushMatrix();
translate(x, y);
rotate(radians(d + frameCount));
ellipse(x, y, fromCenter, fromCenter);
popMatrix();
}
}
}
The values you're passing into the map() function don't make a lot of sense to me:
float fromCenter = map(cSize, 0, d, 1, 100);
The cSize variable bounces from 1 to 10 independent of anything else. The d variable is the distance of each ellipse to the center of the circle, but that's going to be static for each one since you're using the rotate() function to "move" the circle, which never actually moves. That's based only on the frameCount variable, which you never use to calculate the size of your ellipses.
In other words, the position of the ellipses and their size are completely unrelated in your code.
You need to refactor your code so that the size is based on the distance. I see two main options for doing this:
Option 1: Right now you're moving the circles on screen using the translate() and rotate() functions. You could think of this as the camera moving, not the ellipses moving. So if you want to base the size of the ellipse on its distance from some point, you have to get the distance of the transformed point, not the original point.
Luckily, Processing gives you the screenX() and screenY() functions for figuring out where a point will be after you transform it.
Here's an example of how you might use it:
for (int x = -50; x <= 50; x+=100) {
for (int y = -50; y <= 50; y+=100) {
pushMatrix();
//transform the point
//in other words, move the camera
translate(x, y);
rotate(radians(frameCount));
//get the position of the transformed point on the screen
float screenX = screenX(x, y);
float screenY = screenY(x, y);
//get the distance of that position from the center
float distanceFromCenter = dist(screenX, screenY, width/2, height/2);
//use that distance to create a diameter
float diameter = 141 - distanceFromCenter;
//draw the ellipse using that diameter
ellipse(x, y, diameter, diameter);
popMatrix();
}
}
Option 2: Stop using translate() and rotate(), and use the positions of the ellipses directly.
You might create a class that encapsulates everything you need to move and draw an ellipse. Then just create instances of that class and iterate over them. You'd need some basic trig to figure out the positions, but you could then use them directly.
Here's a little example of doing it that way:
ArrayList<RotatingEllipse> ellipses = new ArrayList<RotatingEllipse>();
void setup() {
size(500, 500);
ellipses.add(new RotatingEllipse(width*.25, height*.25));
ellipses.add(new RotatingEllipse(width*.75, height*.25));
ellipses.add(new RotatingEllipse(width*.75, height*.75));
ellipses.add(new RotatingEllipse(width*.25, height*.75));
}
void draw() {
background(0);
for (RotatingEllipse e : ellipses) {
e.stepAndDraw();
}
}
void mouseClicked() {
ellipses.add(new RotatingEllipse(mouseX, mouseY));
}
void mouseDragged() {
ellipses.add(new RotatingEllipse(mouseX, mouseY));
}
class RotatingEllipse {
float rotateAroundX;
float rotateAroundY;
float distanceFromRotatingPoint;
float angle;
public RotatingEllipse(float startX, float startY) {
rotateAroundX = (width/2 + startX)/2;
rotateAroundY = (height/2 + startY)/2;
distanceFromRotatingPoint = dist(startX, startY, rotateAroundX, rotateAroundY);
angle = atan2(startY-height/2, startX-width/2);
}
public void stepAndDraw() {
angle += PI/64;
float x = rotateAroundX + cos(angle)*distanceFromRotatingPoint;
float y = rotateAroundY + sin(angle)*distanceFromRotatingPoint;
float distance = dist(x, y, width/2, height/2);
float diameter = 50*(500-distance)/500;
ellipse(x, y, diameter, diameter);
}
}
Try clicking or dragging in this example. User interaction makes more sense to me using this approach, but which option you choose really depends on what fits inside your head the best.

Need to rotate and move images in processing?

I am fast approaching several deadlines for my highschool graduation project so any advice you can give would be great. My project is to code a movie. The idea is to use processing to move the characters like tokens and also use code to animate things like rain and fire. Right now I am finding it very difficult to move images and/or rotate them. This is a big hurtle for my project. The current code I have for this is butchered and complicated but here it is.
Image of leading lady, Radial: https://www.dropbox.com/s/x3gvendnaeftapj/radialoutlinel.png
/*
Radialrolling
*/
PImage img; // Declare variable "a" of type PImage
float ballX = 10;
float ballY = 200;
float h = 300;
//create a variable for speed
float speedY = 2; // spped set to 0 in order to test rotating. Necessary for rolling motion
float speedX = 0.;
void setup() {
size(800,800);
smooth();
noStroke();
background(0, 0, 0);// Load the image into the program
// change the mode we draw circles so they are
// aligned in the top left
ellipseMode(CORNER);
img = loadImage("radialoutlinel.png");
}
void RadialRoll(){
rotate(0);//if this is anything but 0 ball will appear of screen
image(img, ballX, ballY, h, h); //create a continuos rotation using the new fun
//nctions in the draw things
}
void draw() {
//clear the background and set the fill colour
background(0);
fill(255);
//draw the circle in it's current position
// ellipse(ballX, ballY, h,h);
//add a little gravity to the speed
speedY = speedY + 0;
speedX = speedX + .02;
ballX = ballX + speedX;
RadialRoll();
if (ballX > width - h) {
// set the position to be on the floor
ballX = width - h;
// and make the y speed 90% of what it was,
// but in the opposite direction
speedX = speedX * -1;
//switch the direction
//speedY = speedY;
}
if (ballX > width - h) {
// set the position to be on the floor
ballX = width - h;
// and make the y speed 90% of what it was,
// but in the opposite direction
speedX = speedX * -1;
//switch the direction
//speedY = speedY;
}
else if (ballX <= 0) {
// if the ball hits the top,
// make it bounce off
speedX = -speedX;
}
if (ballY > height - h) {
// set the position to be on the floor
ballY = height - h;
// and make the y speed 90% of what it was,
// but in the opposite direction
speedY = speedY * -1;
//switch the direction
//speedY = speedY;
}
else if (ballY <= 0) {
// if the ball hits the top,
// make it bounce off
speedY = -speedY;
}
}
How can I move images on screen and rotate them with little hassle?
Thank you very much.
-TheIronHobo
First when you look at rotate() function it take radians (values from 0 to TWO_PI) as argument so when you want fluent rotation use something like this
rotate(counter*TWO_PI/360);
Where counter could be integer value increased in every draw() loop. But if you just add this to you code image will be rotating around point [0,0] (upper left corner) and you will not see image for 1/4 of the rotation. To better understanding this you should read this TUTORIAL then you could start with basic rotation:
PImage img;
int counter = 1;
void setup() {
size(800, 800);
smooth();
background(0, 0, 0);
img = loadImage("radialoutlinel.png");
imageMode(CENTER); //you can change mode to CORNER to see the difference.
}
void draw() {
background(0);
fill(255);
counter++;
translate(width/2, height/2);
rotate(counter*TWO_PI/360);
image(img, 0, 0, 300, 300);
}
Then if you want also move image from left to right side you will just adjust translate() first parameter.

Gravity simulation going haywire

I'm currently working on a Processing sketch featuring a very basic gravity simulation (based on an example given in Daniel Schiffman's book Learning Processing) but my gravity keeps behaving in a bizarre way and I'm at a loss to know what to do about it. Here's the simplest example I can come up with:
float x = 50;
float y = 50;
float speed = 2;
float gravity = 0.1;
void setup() {
size(400, 400);
}
void draw() {
background(255);
fill(175);
stroke(0);
ellipseMode(CENTER);
ellipse(x, y, 10, 10);
y = y + speed;
speed = speed + gravity;
//Dampening bounce effect when the ball hits bottom
if (y > height) {
speed = speed * -0.95;
}
}
The above is virtually identical to what's in Schiffman's book aside from a different starting speed and a different window size. It seems to work fine for the first two bounces but on the third bounce the ball becomes stuck to the bottom of the window.
I have no idea where to even begin trying to debug this. Can anyone give any pointers?
If y remains greater than height, your code just keeps flipping the speed over and over without giving the ball a chance to bounce. You want the ball to move away from the boundary whenever it is at or past the boundary.
Setting y to height in the (if y > height) block helps, but the ball never comes to 'rest' (sit on the bottom line when done).
There are two problems with Shiffman's example 5.9 which is where you probably started:
1) y can become greater than (height + speed), which makes it seem to go thud on the ground or bounce wildly
-- fixed with the suggestion
2) The algorithm to update y does things in the wrong order, so the ball never comes to rest
Correct order is:
if it is time to 'bounce
negate speed including dampening (* 0.95)
set y to location of the 'ground'
Add gravity to speed
Add speed to y
This way, when it is time to bounce (y is > height), and speed is positive (going downward):
speed is set to negative (times dampening)
y is set to height
speed is set less negative by the gravity factor
y is made less positive by adding the (still negative) speed
In my example, I didn't want the object to disappear so I use a variable named 'limit' to be the lowest (most positive y) location for the center of the object.
float x = 50;
float y = 50;
float speed = 2;
float gravity = 0.1;
void setup() {
size(400, 400);
y = height - 20;
}
void draw() {
background(255);
fill(175);
stroke(0);
ellipseMode(CENTER);
ellipse(x, y, 10, 10);
float limit = height - (speed + 5);
//Dampening bounce effect when the ball hits bottom
if (y > limit) {
speed = speed * -0.95;
y = limit;
}
speed = speed + gravity;
y = y + speed;
}

Resources