How to change speed of ellipses in processing - processing

I am trying to create an array of circles which all move at different speeds and have different colours using classes which i have done however about 5 seconds into running it for some reason the ellipses all go to the edges of the window and the code doesn't work properly. Below I have provided my code including the class and setup:
circle circles = new circle(1, 8);
void setup() {
size(800, 600);
}
void draw() {
background(255);
circles.display();
circles.bounce();
}
class circle {
int[] posX = new int [10];
int[] posY = new int [10];
float[] speedX = new float[10];
float[] speedY = new float[10];
int[] red = new int [10];
int[] green = new int [10];
int[] blue = new int [10];
circle(float start, float end) {
for (int i = 0; i < 10; i++) {
speedX[i] = random(start, end);
speedY[i] = random(start, end);
posX[i] = int(random(500, 800));
posY[i] = int(random(500, 600));
red[i] = int(random(0, 255));
green[i] = int(random(0, 255));
blue[i] = int(random(0, 255));
}
}
void display() {
for (int i = 0; i < 10; i++) {
fill(red[i], green[i], blue[i]);
ellipse(posX[i], posY[i], 50, 50);
}
}
void bounce() {
for (int i = 0; i < 10; i++) {
posX[i] += speedX[i];
posY[i] += speedY[i];
if (posX[i] - 50 < 0 || posX[i] + 50 > width) {
speedX[i] = -speedX[i];
}
if (posY[i] - 50 < 0 || posY[i] + 50 > height) {
speedY[i] = -speedY[i];
}
}
}
}

The main problem is that you were not setting the balls to be inside the screen again! This is a very common problem, and Dan Shiffman used it to show the new Processing 3 Debugger.
But since i've found many stuff about your code i will also comment other stuff that might help you with programming.
But first let me show you the working code:
int n_of_circles = 10;
Circle[] circles = new Circle[n_of_circles];
void setup() {
size(800, 600);
for (int i = 0; i < n_of_circles; i++) {
circles[i] = new Circle(1, 8);
}
}
void draw() {
background(255);
for (int i = 0; i < n_of_circles; i++) {
circles[i].display();
circles[i].move();
}
}
class Circle {
float posX = random(0, width); //no need to set these value in constructor
float posY = random(0, height); //we can set it here
float speedX = 666; //we will change these on constructor
float speedY = 666; //666 is just a personal convention that i use to indicate that :p
//Similarly, no need to set the color variable in the constructor
//also, lets use a color variable instead of 3 separate variables
color circ_color = color(
(int) random(0, 255),
(int) random(0, 255),
(int) random(0, 255)
);
//defining circle diameter instead of using a literal ("50", in our case)
int diameter = 50;
int radius = diameter/2;
Circle(float min_speed, float max_speed) {
// The purpose of "min_speed" and "max_speed" are clearer than "start" and "end"
speedX = random(min_speed, max_speed);
speedY = random(min_speed, max_speed);
}
void display() {
//this push an pop commands ensure that this fill command won't
//interfere with any other stuff, if you ever reuse this code
pushStyle();
fill( circ_color );
ellipse(posX, posY, diameter, diameter);
popStyle();
}
//notice how i separated the move declartions form the bounce. It's good programming practice
//to keep stuff simpler. Functions should always have one single responsibility.
//In this case it won't helpĀ“much, but we're yoru move function more complex, it would!
void move(){
posX += speedX;
posY += speedY;
bounce();
}
void bounce() {
//note that you were using the diameter, but you should really use the radius!
//if it's touching left or side edges
if (posX - radius < 0 || posX + radius > width) {
speedX *= -1; //inverts the sign
//Here's the actual missing bits!
if (posX - radius < 0 ){ posX = radius; }
if (posX + radius > width ){ posX = width-radius; }
}
//if it's touching top or bottom edges
if (posY - radius < 0 || posY + radius > height) {
speedY *= -1; //inverts the sign
//Here's the actual missing bits!
if (posY - radius < 0 ){ posY = radius; }
if (posY + radius > height ){ posY = height-radius; }
}
}
} //end of class Circle
Just i few suggestions:
The convention is that Class names are upper case. This you you have Circle circles = new Circle(1,5); This is clearer.
Avoid using literals! (writing hard-coded numbers) For example, you we're using "ellipse(posX[i], posY[i], 50, 50);". By using a variable for diameter your code becomes more modular. Should you change the circles diameter, you just alter one line of code!
Use arrays of objects instead of classes that contains other stuff. That's good programming practice as it makes your code easier to understand. Now if you need to group lots of circles you use an array, or you can create another class "Group_of_circles" for ex.
I know i've presented some new concepts/syntaxes and changed a lot to your code, but i tried to comment everything to make it clear and instructive
Since i've already changed much thing i didn't use any Vectors, but when dealing with positions , you really should use PVectors! This free book have a great chapter on them!
Try to find good tutorials about software development. They will teach about godo programming practices like keeping your code as modular as possible and etc. But don't worry, it will come to you natrually over time!
Try learncpp.com, tutorialss 1-10a and 1-4b. Those 2 are part of a c++ tutorial, but are a good starting point and refer to programming in general.

Related

object releases another smaller object?

Can anyone help me?
So, I'm supposed to have a ball that is moving horizontally, such that every time I press the mouse, a ball would get shoot vertically, then slows down due to friction. The vertical ball would stay in the old position but the player would reset.
How do I go about doing that without using classes?
Here my code so far:
boolean circleupdatetostop = true;
float x = 100;
float yshot = 880;
float speedshot = random(4,10);
float speedx = 6;
void setup() {
size(1280,960);
}
void draw() {
background(255);
stroke(0);
fill(0);
circle(x,880,80);
if (x > width || x < 0 ) {
speedx = speedx * -1;
}
if (circleupdatetostop) {
x = x + speedx;
}
if (circleupdatetostop == false) {
float locationx = x;
stroke(0);
fill(255,0,255);
circle(locationx,yshot,30);
yshot = yshot - speedshot;
}
}
void mousePressed () {
circleupdatetostop = !circleupdatetostop;
}
I'm not entirely sure if this is what you meant, but you could achieve shooting multiple balls by using ArrayList as well as processing's PVector to better handle the x and y coordinate pairs. If you wanted to look at classes, see this post.
import java.util.*;
// Whether the ball is moving or not
boolean circleupdatetostop = true;
// Information about the main_ball
PVector position = new PVector(100, 880);
PVector speed = new PVector(6, 0);
float diameter = 80;
// Information about the sot balls
ArrayList<PVector> balls_loc = new ArrayList<PVector>();
ArrayList<PVector> balls_speed = new ArrayList<PVector>();
float diameter_shot = 30;
float friction = 0.994;
void setup() {
size(1280, 960);
}
void draw() {
background(255);
stroke(0);
fill(0);
circle(position.x, position.y, diameter);
// Remember to consider the radius of the ball when bouncing off the edges
if (position.x + diameter/2 > width || position.x - diameter/2 < 0 ) {
speed.mult(-1);
}
if (circleupdatetostop) {
position.add(speed);
}
// Cycle through the list updating their speed and draw each ball
for (int i = 0; i<balls_loc.size(); i++) {
balls_speed.get(i).mult(friction+random(-0.05, 0.05));
balls_loc.get(i).add(balls_speed.get(i));
stroke(0);
fill(255, 0, 255);
circle(balls_loc.get(i).x, balls_loc.get(i).y, diameter_shot);
}
}
void mousePressed(){
// Add a new ball to be drawn
if(circleupdatetostop){
balls_loc.add(new PVector(position.x, position.y));
balls_speed.add(new PVector(0, random(-4, -10)));
}
circleupdatetostop = !circleupdatetostop;
}

Trying to make a ball bounce on the screen in processing using classes

I am working on making a single ball bounce all over the screen but I have an issue with making the ball bounce the bounce() function is responsible for making the ball bounce but I run into an array out of bounds exception despite only going through 1 element in the array. I have provided the code below. This code utilizes 2 classes (Ball_Usage and Ball).
Ball_Usage code:
Ball ball1;
void setup(){
size(500,500);
ball1 = new Ball();
}
void draw(){
background(255);
ball1.bounce();
}
Ball:
class Ball{
float [] xPos = {};
float [] yPos = {};
float [] dia = {};
float [] xSpeed = {};
float [] ySpeed = {};
Ball(){
}
Ball(float x, float y, float argDia){
xPos = append(xPos, x);
yPos = append(yPos, y);
dia = append(dia, argDia);
}
void bounce(){
for(int i=0; i<1; i++){
ellipse(xPos[i], yPos[i], 50, 50);
xPos[i] += xSpeed[i];
yPos[i] += ySpeed[i];
if(xPos[i]<0 || xPos[i]>=width){
xSpeed[i] = -xSpeed[i];
}
if(yPos[i]<0 || yPos[i]>=height){
ySpeed[i] = -ySpeed[i];
}
}
}
}
I believe the confusion comes from the fact that your class has two constructors:
an empty constructor (that takes no arguments): Ball()
a constructor with position and argDia (guessing diameter ?) arguments: Ball(float x, float y, float argDia)
In setup() you call the empty constructor:
ball1 = new Ball();
This means the five float arrays still have a length of 0, hence the out of bounds exception.
Even if you call the position + diameter version of the constructor, the xSpeed, ySpeed arrays will still have length 0.
You could fix this by initialising the two two arrays as well as using this version of the constructor:
Ball ball1;
void setup() {
size(500, 500);
//ball1 = new Ball();
ball1 = new Ball(250, 250, 50);
}
void draw() {
background(255);
ball1.bounce();
}
class Ball {
float [] xPos = {};
float [] yPos = {};
float [] dia = {};
float [] xSpeed = {};
float [] ySpeed = {};
Ball() {
}
Ball(float x, float y, float argDia) {
xPos = append(xPos, x);
yPos = append(yPos, y);
dia = append(dia, argDia);
xSpeed = append(xSpeed, random(-1, 1));
ySpeed = append(ySpeed, random(-1, 1));
}
void bounce() {
for (int i=0; i<1; i++) {
ellipse(xPos[i], yPos[i], 50, 50);
xPos[i] += xSpeed[i];
yPos[i] += ySpeed[i];
if (xPos[i]<0 || xPos[i]>=width) {
xSpeed[i] = -xSpeed[i];
}
if (yPos[i]<0 || yPos[i]>=height) {
ySpeed[i] = -ySpeed[i];
}
}
}
}
This will work, however there is still a bit of confusion: why use the arrays at all if you're only looping once for the first element ? It makes the arrays and for loop mostly redundant.
You might choose to keep if you plan to change the diameter over time (which in your code is hardcoded to 50), maybe positions and velocities and render a changing history of a ball.
If you don't, you could simply use float properties instead of arrays:
Ball ball1;
void setup() {
size(500, 500);
ball1 = new Ball();
}
void draw() {
background(255);
ball1.bounce();
}
class Ball {
float xPos;
float yPos;
float diameter = 50;
float xSpeed;
float ySpeed;
Ball() {
xPos = width / 2;
yPos = height / 2;
xSpeed = random(-1, 1);
ySpeed = random(-1, 1);
}
void bounce() {
ellipse(xPos, yPos, diameter, diameter);
xPos += xSpeed;
yPos += ySpeed;
if (xPos < 0 || xPos >= width) {
xSpeed = -xSpeed;
}
if (yPos < 0 || yPos >= height) {
ySpeed = -ySpeed;
}
}
}
This looks more similar to the Bounce Processing Example.
You can at a later stage make an array of Ball objects.
Additionally it's worth formatting code as it saves you time reading/scrolling through it and visually it's easier to scan the structure of the program (how each part fits in) and therefore makes it easier to debug/run mentally. It takes no effort as you can simply press Ctrl+T on Windows/Linux or CMD+T on OSX. On the long run this will pay off, especially as programs get longer and more complex as you spend more time reading code than writing code. It's a good habit to pickup early while learning to code. Have fun!

(Processing) GROUP PShape getWidth() or width is 0.0

I want to get the width and the height of a GROUP PShape, but I only get 0.0.
For example:
// Example code from "https://processing.org/reference/PShape_addChild_.html"
PShape house;
void setup() {
size(200, 200);
// Make a group PShape
house = createShape(GROUP);
// Make three shapes
PShape path = createShape();
path.beginShape();
path.vertex(-20, -20);
path.vertex(0, -40);
path.vertex(20, -20);
path.endShape();
PShape rectangle = createShape(RECT, -20, -20, 40, 40);
PShape circle = createShape(ELLIPSE, 0, 0, 20, 20);
// Add all three as children
house.addChild(path);
house.addChild(rectangle);
house.addChild(circle);
println(house.width, house.getWidth());
println(house.height, house.getHeight());
}
void draw() {
background(52);
translate(mouseX, mouseY);
shape(house);
}
In this code, println(house.width, house.getWidth()); and println(house.height, house.getHeight()); show 0.0 0.0
So, how can I get the width and the height of any PShape?
Edit
Following the advice from #Rabbid76, I have created a getBoundingBoxLimits() function:
float[][] getBoundingBoxLimits(PShape s){
float[][] coords = {{1000000.0, -1000000.0}, {1000000.0, -1000000.0}};
// coords represents {{min_x, max_x}, {min_y, max_y}}
float ii, jj;
for(int i=0; i<1000; i++){
for(int j=0; i<1000; j++){
ii = i*1.0;
jj = j*1.0;
if(s.contains(ii,jj)){ // contains() expects floats, not ints
if(ii < coords[0][0]) { coords[0][0] = ii; }
if(ii > coords[0][1]) { coords[0][1] = ii; }
if(jj < coords[1][0]) { coords[1][0] = jj; }
if(jj > coords[1][1]) { coords[1][1] = jj; }
}
}
}
return coords;
}
But it returns an IllegalArgumentException: The contains() method is only implemented for paths..
So, at first glance, it seems that I cannot determine if a (x, y) point is in any PShape other than a PATH PShape.
Anyway, I am expecting a more straightforward way of getting the width and the height of any PShape (as I am sure this information is stored inside any of these objects).

Processing detecct whether mouse is inside a bouncing circle when clicked

Trying to determine whether the mouse has been clicked within a certain ball and when it is clicked I want to display text that relates to that specific ball, this is what I have so far any help would be appreciated.
int rad = 60; // Width of the shape
float xpos1, ypos1; // Starting position of shape
float xspeed = 4; // Speed of the shape
float yspeed = 4; // Speed of the shape
int xdirection = 1; // Left or Right
int ydirection = 1; // Top to Bottom
boolean overBox1 = false;
void setup()
{
size(1200, 800);
noStroke();
frameRate(30);
ellipseMode(RADIUS);
// Set the starting position of the shape
xpos1 = width/2;
ypos1 = height/2;
}
void draw()
{
background(102);
circleone();
}
void circleone()
{
xpos1 = xpos1 + ( xspeed * xdirection );
ypos1 = ypos1 + ( yspeed * ydirection );
if (xpos1 > width-rad || xpos1 < rad) {
xdirection *= -1;
}
if (ypos1 > height-rad || ypos1 < rad) {
ydirection *= -1;
}
ellipse(xpos1, ypos1, rad, rad);
}
void mouseClick()
{
if (overCircle(xpos1,ypos1,rad)==true)
{
println("YO");
}
}
boolean overCircle(float x, float y, int radius) {
float disX = x - mouseX;
float disY = y - mouseY;
if (sqrt(sq(disX) + sq(disY)) <radius) {
return true;
} else {
return false;
}
}
This logic seems overcomplicated:
float disX = x - mouseX;
float disY = y - mouseY;
if (sqrt(sq(disX) + sq(disY)) <radius)
You could just use the dist() function instead:
return dist(x, y, mouseX, mouseY) < radius;
Then if you want to display some text when the ball is clicked, you're going to have to add more than a println() statement. You might set a boolean variable to true, and then in the draw() function you'd check that variable and draw something to the screen when it's true.
If you're trying to get many clickable balls on the screen, then you might think about creating classes that represent a ball and putting your logic in there.
But you haven't really asked a question. You've posted some code, haven't told us what you expect it to do, what it does instead, or how those two things are different. Stack Overflow isn't really designed for general "how do I do this" type questions. It's for more specific "I tried X, expected Y, but got Z instead" type questions. So you'll have much better luck if you post a MCVE instead of your entire project and ask a specific question about a specific line of code. Good luck.

Processing: How can I make multiple elements in a for() loop move to one location then return?

I have a grid of ellipses generated by two for() loops. What I'd like to do is have all of these ellipses ease into mouseX and mouseY when mousePressed == true, otherwise return to their position in the grid. How can I go about this? I've started with this template, which doesn't work as I can't figure out how affect the position of the ellipses, but the easing is set up.
float x;
float y;
float easeIn = 0.01;
float easeOut = 0.08;
float targetX;
float targetY;
void setup() {
size(700, 700);
pixelDensity(2);
background(255);
noStroke();
}
void draw() {
fill(255, 255, 255, 80);
rect(0, 0, width, height);
for (int i = 50; i < width-50; i += 30) {
for (int j = 50; j < height-50; j += 30) {
fill(0, 0, 0);
ellipse(i, j, 5, 5);
if (mousePressed == true) {
// go to mouseX
targetX = mouseX;
// ease in
float dx = targetX - x;
if (abs(dx) > 1) {
x += dx * easeIn;
}
//go to mouseY
targetY = mouseY;
// ease in
float dy = targetY - y;
if (abs(dy) > 1) {
y += dy * easeIn;
}
} else {
// return to grid
targetX = i;
// ease out
float dx = targetX - x;
if (abs(dx) > 1) {
x += dx * easeOut;
}
// return to grid
targetY = j;
// ease out
float dy = targetY - y;
if (abs(dy) > 1) {
y += dy * easeOut;
}
}
}
}
}
Any help would be greatly appreciated. I'm not sure in which order to do things/which elements should be contained in the loop.
Thanks!
You're going to have to keep track of a few things for each dot: its "home" position, its current position,its speed, etc.
The easiest way to do this would be to create a class that encapsulates all of that information for a single dot. Then you'd just need an ArrayList of instances of the class, and iterate over them to update or draw them.
Here's an example:
ArrayList<Dot> dots = new ArrayList<Dot>();
void setup() {
size(700, 700);
background(255);
noStroke();
//create your Dots
for (int i = 50; i < width-50; i += 30) {
for (int j = 50; j < height-50; j += 30) {
dots.add(new Dot(i, j));
}
}
}
void draw() {
background(255);
//iterate over your Dots and move and draw each
for (Dot dot : dots) {
dot.stepAndRender();
}
}
class Dot {
//the point to return to when the mouse is not pressed
float homeX;
float homeY;
//current position
float currentX;
float currentY;
public Dot(float homeX, float homeY) {
this.homeX = homeX;
this.homeY = homeY;
currentX = homeX;
currentY = homeY;
}
void stepAndRender() {
if (mousePressed) {
//use a weighted average to chase the mouse
//you could use whatever logic you want here
currentX = (mouseX+currentX*99)/100;
currentY = (mouseY+currentY*99)/100;
} else {
//use a weighted average to return home
//you could use whatever logic you want here
currentX = (homeX+currentX*99)/100;
currentY = (homeY+currentY*99)/100;
}
//draw the ellipse
fill(0, 0, 0);
ellipse(currentX, currentY, 5, 5);
}
}
Note that I'm just using a weighted average to determine the position of each ellipse, but you could change that to whatever you want. You could give each ellipse a different speed, or use your easing logic, whatever. But the idea is the same: encapsulate everything you need into a class, and then put the logic for one dot into that class.
I'd recommend getting this working for a single dot first, and then moving up to getting it working with multiple dots. Then if you have another question you can post the code for just a single dot instead of a bunch. Good luck.

Resources