We closed this forum 18 June 2010. It has served us well since 2005 as the ALPHA forum did before it from 2002 to 2005. New discussions are ongoing at the new URL http://forum.processing.org. You'll need to sign up and get a new user account. We're sorry about that inconvenience, but we think it's better in the long run. The content on this forum will remain online.
Page Index Toggle Pages: 1
magnets (Read 1241 times)
magnets
Oct 25th, 2005, 7:15am
 
I'm looking into creating a class that will gravitate toward an area or mouseX/Y but then be repusled by the same area if mouse is clicked or something similar.

I've seen some nice examples around, but some of the math is a little beyond me (atan, etc).. and I would like the objects to hover around the attracted area somewhat tightly but without stopping altogether.

Help = much thanks Smiley

Explinations about atan or links to simple trig sites would be good too
Re: magnets
Reply #1 - Oct 25th, 2005, 7:56am
 
If you know nothing about sine/cosine/tan: http://www.mathsisfun.com/sine-cosine-tangent.html

atan or arctan is the reverse of tan.  For example, the expression atan(.123) = r simply asks:  What angle "r" has the tangent of .123?
The idea is the same for functions asin/arcsin, acos, etc.
The concepts are easy, but you really have to look at examples to see how they are used in real-life/simulated physics
Re: magnets
Reply #2 - Oct 25th, 2005, 3:28pm
 
It's probably a lot easier to think of x and y as separate rather than worrying about trigonometry too much. It sounds like you need two attractors (two magnets). When you press the mouse down the other attractor is activated. Below is a simplified code of this. You could copy the x stuff into a y function to get two dimensional movement.

The second magnet is on a timer. Instead of either one being on or the other being off you might want to experiment with either magnet increasing or decreasing in strength (could use more timers and divide by their value).
Code:

Particle [] particle;
int timer = 0;
boolean toMouse = true;
void setup(){
size (400,400);
particle = new Particle[20];
for (int i = 0; i < particle.length; i++)
particle[i] = new Particle();
}
void draw(){
background(200,100,50);
for(int i = 0; i < particle.length; i++){
particle[i].draw();
particle[i].drift();
}
if(timer == 0)
toMouse = true;
else{
toMouse = false;
timer--;
}
}
void mousePressed(){
timer = 50;
}
class Particle{
float x,y,attractorX;
Particle(){
x = random(width);
attractorX = random(width);
y = random(height);
toMouse = true;
}
void drift(){
float delta = 0.0;
//decelerate - divide difference
if(toMouse) delta = (mouseX - x)/16;
//accelerate - divide difference and subtract from difference
else delta = (attractorX - x) - ((attractorX - x)/1.5);
x += delta;
}
void draw(){
ellipse(x,y,10,10);
rect(attractorX,y,10,10);
}
}
Page Index Toggle Pages: 1