GigaPudding
GigaPudding

Reputation: 45

checking edge for circular movement

I want to make my dot program turn around when they reach edge

so basically i just simply calculate x = width/2+cos(a)*20; y = height/2+sin(a)*20; it's make circular movement. so i want to make this turn around by checking the edge. i also already make sure that y reach the if condition using println command

class particles {
float x, y, a, r, cosx, siny;
particles() {
x = width/2; y = height/2; a = 0; r = 20;
}
void display() {
ellipse(x, y, 20, 20);
}
void explode() {
a = a + 0.1;
cosx = cos(a)*r;
siny = sin(a)*r;
x = x + cosx;
y = y + siny;
}

void edge() {
if (x>width||x<0) cosx*=-1;
if (y>height||y<0) siny*=-1;
 }
}   
//setup() and draw() function

particles part;
void setup(){
size (600,400);
part = new particles();
}
void draw(){
background(40);
part.display();
part.explode();
part.edge();
}

they just ignore the if condition

Upvotes: 2

Views: 51

Answers (1)

John Coleman
John Coleman

Reputation: 52008

There is no problem with your check, the problem is with the fact that presumably the very next time through draw() you ignore what you did in response to the check by resetting the values of cosx and siny.

I recommend creating two new variables, dx and dy ("d" for "direction") which will always be either +1 and -1 and change these variables in response to your edge check. Here is a minimal example:

float a,x,y,cosx,siny;
float dx,dy;

void setup(){
  size(400,400);
  background(0);
  stroke(255);
  noFill();
  x = width/2; 
  y = height/2;
  dx = 1;
  dy = 1;
  a = 0;
}

void draw(){
  ellipse(x,y,10,10);
  cosx = dx*20*cos(a); 
  siny = dy*20*sin(a);
  a += 0.1;
  x += cosx; 
  y += siny;
  if (x > width || x < 0)
    dx = -1*dx;

  if (y > height || y < 0)
    dy = -1*dy;
}

When you run this code you will observe the circles bouncing off the edges:

enter image description here

Upvotes: 3

Related Questions