Reputation: 27
I want the particle object to simply follow the mouseX and mouseY location on movement. Can I replace the "origin" values with a mouseX and Y somehow?
void run() {
update();
display();
}
// Method to update position
void update() {
velocity.add(acceleration);
location.add(velocity);
lifespan -= 2.0;
}
// Method to display
void display() {
stroke(0, lifespan);
strokeWeight(2);
fill(127, lifespan);
ellipse(location.x, location.y, 12, 12);
}
// Is the particle still useful?
boolean isDead() {
if (lifespan < 0.0) {
return true;
} else {
return false;
}
}
}
Upvotes: 1
Views: 1261
Reputation: 3820
Processing's lerp()
function is suitable for this (as you're looking for the particle to lerp towards the mouse cursor).
posX = lerp(posX, mouseX, 0.5);
posY = lerp(posY, mouseY, 0.5);
The final parameter (0.5 here) is the amount to interpolate between the two values where 0.1 is very near the current particle position; 0.5 is halfway in-between the particle position and cursor position, etc.
Lerp is short for linear interpolation. You may find other forms of interpolation (or easing) to be more suitable to model the movement of your particle, such those from the penner easing collection:
Upvotes: 0
Reputation: 518
This example is even simpler and easier to understand - hope it helps.
float x;
float y;
float easing = 0.05;
void setup() {
size(640, 360);
noStroke();
}
void draw() {
background(51);
float targetX = mouseX;
float dx = targetX - x;
x += dx * easing;
float targetY = mouseY;
float dy = targetY - y;
y += dy * easing;
ellipse(x, y, 66, 66);
}
Upvotes: 2
Reputation: 681
Take a look at this example:
PVector pos;
PVector vel;
PVector acc;
void setup()
{
size(400, 400);
pos = new PVector(width / 2, height / 2);
vel = new PVector(0, 0);
acc = new PVector(0, 0);
}
void draw()
{
background(255);
followMouse();
update();
ellipse(pos.x, pos.y, 10, 10);
}
void followMouse()
{
PVector mouse = new PVector(mouseX, mouseY);
//calculating what acceleration would be needed to instantly reach the mouse
acc = mouse.sub(pos);
//reducing the acceleration to not reach the mouse instantly
acc.mult(0.1);
}
void update()
{
vel.add(acc);
//dampening the velocity, so the ball gets slower when close to the mouse
vel.mult(0.8);
pos.add(vel);
}
Upvotes: 2