We are about to switch to a new forum software. Until then we have removed the registration on this forum.
I am trying to make my object stay within the canvas boundaries, its not working! I haven't a clue why.. any ideas?
Wanderer[] wanderer = new Wanderer[1];
void setup()
{
size(1280, 720);
background(0);
fill(250);
noStroke();
for (int i=0; i<wanderer.length; i++)
{
wanderer[i] = new Wanderer(random(width), random(height));
}
}
void draw()
{
background(0);
for (int i=0; i<wanderer.length; i++)
{
wanderer[i].stayInsideCanvas();
wanderer[i].move();
ellipse(wanderer[i].getX(), wanderer[i].getY(), 50, 50);
}
}
class Wanderer
{
float x;
float y;
float wander_theta;
float wander_radius;
// bigger = more edgier, hectic
float max_wander_offset = 0.3;
// bigger = faster turns
float max_wander_radius = 20.5;
Wanderer(float _x, float _y)
{
x = _x;
y = _y;
wander_theta = random(TWO_PI);
wander_radius = random(max_wander_radius);
}
void stayInsideCanvas()
{
x %= width;
y %= height;
}
void move()
{
float wander_offset = random(-max_wander_offset, max_wander_offset);
wander_theta += wander_offset;
x += cos(wander_theta);
y += sin(wander_theta);
}
float getX()
{
return x;
}
float getY()
{
return y;
}
}
Answers
https://Processing.org/reference/constrain_.html
Try running these lines in a separate sketch:
Constrain, as GoTo mentioned, will do exactly what you want. You could even include the radius of your ellipse so the whole ellipse body is inside the sketch at all times.
x=constrain(x,r,width-r);
Kf
Constrain worked perfectly, thanks!