What do i need to change to make the code work? - processing

I started programming this pong game for CS class. I want to have the ball starting off in the center of the field so I used:
ellipse (width/2, height/2, 15, 15);
I want to make the game start once I press the space key. In order to do that I used:
if (keyPressed == true) {ellipse (ballX, ballY, 15, 15); fill (0, 255, 0);}
However it does not work. Can someone please help me figure out what is wrong with my code? Please consider that this is not a JavaScript but a Processing question.
Here is my entire code so far:
float ballX = 15, ballY = 15, dX = 15, dY = 15; // variables for the ball
float paddleX; // variables for the paddles
int mouseY; // variable to make the pong move with the mouse movement
boolean key, keyPressed;
void setup() {
size (1500,1100); // the field is going to be 1500x110px big
paddleX = width - 40;
ballX = 15; ballY = 15;
}
void draw() {
background(0); // black background
ellipse (width/2, height/2, 15, 15); // this is the starting point of the ball
if (keyPressed == true) { ellipse (ballX, ballY, 15, 15); fill (0, 255, 0); } // the game will only start when a key is pressed
if (ballX > width || ballX < 0) { dX = -dX; } // if the ball reaches the right or left wall it will switch directions
if (ballY > height || ballY < 0) { dY = -dY; }// if the ball reaches the upper or lower wall it will switch directions
ballX = ballX + dX; ballY = ballY + dY; // the ball with move with the speed set as dX and dY
rect(paddleX/58, mouseY, 20, 100); fill (255,10,20); // green pong
rect(paddleX, mouseY, 20, 100); fill (60,255,0); // red pong
}

The answer to this question is the same as the answer to your other question: you need to store the state of your sketch in variables, then you need to draw each frame based on that state, and finally you need to change those variables to change the state of your game.
Here's a simple example that only draws an ellipse after you press a key:
boolean playing = false;
void keyPressed() {
playing = true;
}
void draw() {
background(0);
if (playing) {
ellipse(width/2, height/2, 50, 50);
}
}
In this example, the playing variable is my state. I then update that state in the keyPressed() function, and I use that state to determine what I draw in my draw() function. You'll have to extrapolate a bit, but this process of breaking your problem down into a state, changing that state, and drawing that state is the answer to all of your questions.

Related

Interfering keys in Processing 2

I'm trying to activate different visuals by pressing different keys. For example, when I press "z" or "Z", an ellipse on a specific position flows down, leaving a trace behind. If I wait for it to reach the canvas border, there's no problem but when I press "0" which activates another ellipse on another position to do the same thing, the ellipse of "z"/"Z" stops flowing. It also happens when I press the same key before the ellipse reaches canvas border. How can I fix this? When I started to code this, I didn't know classes and objects, then I learned and tried to solve it by using creating an object but it got worse, ellipses didn't work at all. I want the first ellipse to continue until the border even if I press another key while it's on its way.
Another thing is I wanted them to fade out after a short time, so I drew semi-transparent rectangles on canvas which seems very primitive to me. Would you suggest a different way? This is less important but it would be better to have them completely fade over time rather than leaving a slight trace.
Here's my code, I cleaned irrelevant parts to make it look more understandable:
void setup() {
size(640, 500);
background(bgRenk);
frameRate(60);
colorMode(HSB);
noStroke();
}
int bgRenk = #e7e7e7;
int C3Yer;
int C3Y;
int Fd6Yer;
int Fd6Y;
void draw() {
// This part probably sucks because it's a primitive solution to make ellipses fade out by putting semi-transparent rectangles on the canvas.
fill(bgRenk, 10);
rect(0, 0, 640, 500);
// I basically map x and y positions to hue and opacity.
float C3Renk= map(C3Yer, 0, width, 0, 255);
float C3Opak = map(C3Y, height, 0, 0, 200);
// When z/Z is pressed, an ellipse appears and goes down, leaving trace behind.
if (key == 'z' || key == 'Z') {
C3Yer = 10;
fill(C3Renk, 255, 255, C3Opak);
ellipse(C3Yer, C3Y, 20, 20);
C3Y += 20;
}
if (key == '0') {
// Same mapping and ellipse thing.
float Fd6Renk= map(Fd6Yer, 0, width, 0, 255);
float Fd6Opak = map(Fd6Y, height, 0, 0, 200);
Fd6Yer = 630;
fill(Fd6Renk, 255, 255, Fd6Opak);
ellipse(Fd6Yer, Fd6Y, 20, 20);
Fd6Y += 20;
}
}
void keyPressed() {
if (key == 'z' || key == 'Z') {
// When z/Z is pressed, y position of those ellipses are reset.
C3Y = 10;
}
if (key == '0') {
// Same reset thing.
Fd6Y = 10;
}
}
Thank you for your time.
Problem with creating new ellipse while other is still flowing is with variable key which always contains the value of the most recent key used (for more see). So when you press any key after "z" your ellipse will stop being drawn.
You can avoid this using global variables indicating which ellipses should be drawn.
But I would suggest using creating objects that will have defined state (position, color, opacity) and will be stored inside array or list. It will also help you with fading so find a time and read more about classes and objects. On processing site you can find nice tutorials like this one
But because you sad you already tried creating objects and i don't works I will give you few tips and basic example of such a class:
class Ball {
float x, y; // position of ball
color col = 10; // color of ball
int opac = 255; // opacity of ball
Ball(float _x, float _y) {
x = _x;
y = _y;
}
void move() {
y += 20;
opac -= 10;
}
void display() {
fill(col, 255, 255, opac);
ellipse(x, y, 20, 20);
}
}
Then you can create new ball objects:
void mousePressed() {
//this will create new ball on mouse position
balls.add( new Ball(mouseX, mouseY) );
}
and store them into ArrayList like this:
ArrayList<Ball> balls = new ArrayList();
Last thing that you need to do is display and move all balls within draw method.
for (Ball b : balls) // for each ball in list
{
b.display(); // first display ball
b.move(); // move and change opacity
}
This is very basic example and should be improved but I hope it will help you with understanding of classes.

Processing Joystick beginner

How can I make the mouse move like a joystick. Here is a example of what I mean except this only moves to the right and when the mouse is all the way to the right it stops. I want the circle to stop if the mouse is at the center and move where ever the mouse is.
float ballX = 0; // need to keep track of the ball's current position
float ballY = 150;
void setup() {
size(300,300); // standard size
}
void draw() {
background(200); // dull background
float speed = 2.0 * ( mouseX / (width*1.0) );
println("speed is " + speed); // print just to check
ballX = ballX + speed; // adjust position for current movement
fill(255,0,0);
ellipse(ballX, ballY, 20,20);
}
You want to check the mouseX position against the center of the window, which is width/2.
To find the relative position of the mouse, simply subtract that center position from your mouse position. That way when the mouse is to the left of the center, that value is negative, and your ball will move to the left.
You might also want to keep your ball on the screen.
float ballX = 0; // need to keep track of the ball's current position
float ballY = 150;
void setup() {
size(300,300); // standard size
}
void draw() {
float centerX = width/2;
float maxDeltaMouseX = width/2;
float deltaMouseX = mouseX-centerX;
float speedX = deltaMouseX/maxDeltaMouseX;
background(200); // dull background
println("speed is " + speedX); // print just to check
ballX = ballX + speedX; // adjust position for current movement
//keep ball on screen
if(ballX < 0){
ballX = 0;
}
else if(ballX > width){
ballX = width;
}
fill(255,0,0);
ellipse(ballX, ballY, 20,20);
}

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.

make curtain like behaviour in drawing of lines

I am new to Processing.js and need a little bit support with this issue. I have made a HTML-Canvas animation where I have lines with a curtain like behavior which can be seen here:
Click
this is made with a canvas plugin called Paper.js
I now want to get similar effect on processing but don't really know how to figure it out. My attempt was:
float x;
float y;
void setup() {
size(1024, 768);
strokeWeight(2);
background(0, 0, 0);
}
void mouseMoved() {
x = mouseX;
y = mouseY;
}
void draw() {
background(0);
line(50, 50, x += x - x/5, y += y - y/5);
stroke(255, 255, 255);
line(50, 700, x += x - x/15, y += y - y/15);
stroke(255, 255, 255);
line(75, 50, x += x - x/25, y += y - y/25);
stroke(255, 255, 255);
line(75, 700, x += x - x/35, y += y - y/35);
// and so on, would create it within a loop
}
So what I am trying to do is basically get the same effect which I have done in HTML and adapt it in Processing.js.
Thanks in advance.
I'd strongly recommend ignoring the paper.js and reimplementing this properly. We're seeing a sequence of lines that connect to a historical line of coordinates, based on mouse position, so let's just implement that:
class Point {
float x, y;
Point(float _x, float _y) { x=_x; y=_y; }}
// our list of historical points
ArrayList<Point> points;
// the horizontal spacing of our lines has fixed interval
float interval;
// how many lines do we want to draw?
int steps = 50;
void setup() {
size(500, 500);
// initialise the "history" as just the midpoint
points = new ArrayList<Point>();
for (int i=0; i<steps; i++) {
points.add(new Point(width/2, height/2));
}
// compute the horizontal interval, because it's
// width-dependent. Never hard code dependent values.
interval = width/(float)steps;
// the lower we set this, the slower it animates.
frameRate(60);
}
void draw() {
// white background, black lines
background(255);
stroke(0);
// for each historic point, draw two
// lines. One from height 0 to the point,
// another from height [max] to the point.
Point p;
for (int i=0; i<steps; i++) {
p = points.get(i);
line(interval/2 + i*interval, 0, p.x, p.y);
line(interval/2 + i*interval, height, p.x, p.y);
}
// when we move the mouse, that counts as a new historic point
points.remove(0);
points.add(new Point(mouseX, mouseY));
}
Sketch running in the browser: http://jsfiddle.net/M2LRy/1/
(You could speed this up by using a round-robin array instead of an ArrayList, but ArrayLists are pretty convenient here)

Breakout (the game) in Processing

So, I am creating the game breakout in processing (programming language) but can't quite figure out a function to check for collision against the bat.
So far the section I have written for collision against the bat only collides the ball against the base and returns it in the opposite direction. For now, the game is a never ending phenomenon where the ball just collides with the walls. What I am trying to do is, collide the ball against the bat.
Oh this is my homework, so just please point me in the right direction instead of doing it for me.
Here's the code:
// Basic Breakout game
// Code from Matthre Yee-King
// brick position
float brickX;
float brickY;
// brick width and height
float brickH;
float brickW;
// ball position
float ballX;
float ballY;
// ball diameter
float ballD;
// ball direction
float ballDx;
float ballDy;
// bat position
float batX;
//bat width
float batW;
float batH;
//bat colour
float batB;
void setup() {
size (500, 500, P2D);
// set sizes of game items
brickW = 100;
brickH = 50;
batW = 100;
batH = 25;
ballD = 25;
batB = 255;
// random brick position
brickX = random(0, width - brickW);
brickY = random (0, height / 2);
// bat in the centre
batX = (width/2) - (batW/2);
// ball atop bat
ballX = batX + (batW/2);
ballY = height - batH - (ballD/2);
// ball movement
ballDx = random(-5, 5);
ballDy = -5;
rectMode(CORNER);
ellipseMode(CENTER);
}
void draw() {
// check for ball collision
// with top or sides of bat
checkBallAgainstBat();
// check for ball collision with
// left right and top walls
// and bounce
checkBallAgainstWalls();
// check ball against brick
checkBallAgainstBrick();
// move the ball
ballX += ballDx;
ballY += ballDy;
background(0);
// draw the bat
fill(0, 255, 0);
rect(batX, height - batH, batW, batH);
// draw the brick
fill(0, 0, batB);
batB = (batB + 10) % 255;
rect(brickX, brickY, brickW, brickH);
// draw the ball
fill(255, 0, 0);
ellipse(ballX, ballY, ballD, ballD);
if (keyCode == 37) { // left cursor key
batX -= 10;
// keep it on the screen
if (batX < 0) {
batX = 0;
}
}
if (keyCode == 39) {
batX += 10;
if (batX > (width - batW)) {
batX = width - batW;
}
}
}
// when they let go of the key, reset the keyCode
void keyReleased() {
keyCode = -1;
}
// this function checks if the ball has hit the top or sides of the bat and
// updates its direction as appropriate so the ball bouncs off the bat
void checkBallAgainstBat() {
if (ballY + ballD > height - batH) {
ballDy *= -1;
}
}
// this function checks if the ball has hit the brick. It should bounce off
// the brick and return true if so
boolean checkBallAgainstBrick() {
return false;
}
// this function checks if the ball has hit the top, left or right
// walls and update its
// direction as appropriate so the ball bounces off the walls
void checkBallAgainstWalls() {
if (ballX + ballD > width) {
ballDx *= -1;
}
if (ballX - ballD < 0) {
ballDx *= -1;
}
if (ballY - ballD < 0) {
ballDy *= -1;
}
}
Since the bat in breakout is a fixed width, your collision detection can be quite simple (in pseudo-code):
if (lower_edge(ball) > top_edge(bat)) {
// the ball has entered territory where it might have collided
if ((left_edge(ball) <= right_edge(bat)) && (right_edge(ball) >= left_edge(bat))) {
// the ball's within the horizontal bounds of the bat, so it's a "hit"
... calculate deflection ...
} else {
// oops, ball's gone past the bat and wasn't hit
strike_out();
} else {
// ball's still above the bat somewhere. do nothing
}
In english: If the ball's lower edge has gone past where the top edge of the bat is, we've POSSIBLY got a collision. This is only checking the vertical axis of the play field. You then check if the left or right edges of the ball fall within the horizontal location of the bat. If neither side of the ball overlaps the bat, then you've lost. Otherwise you've collided and you do the collision detection.

Resources