im not that good in english, sorry.
so i have ellipse that moves from the center to the edges. I need it to move back to the center when I click the mouse

``````int rad = 40;        // Width of the shape
float xpos, ypos;    // Starting position of shape

float xspeed = 4.8;  // Speed of the shape
float yspeed = 4;  // Speed of the shape

int xdirection = 1;  // Left or Right
int ydirection = 1;  // Top to Bottom

void setup()
{
size(500, 500);
frameRate(60);
stroke(1);
// Set the starting position of the shape
xpos = width/2;
ypos = height/2;

}

void draw()
{
background(0);

// Update the position of the shape
xpos = xpos + ( xspeed * xdirection );
ypos = ypos + ( yspeed * ydirection );

xdirection *= -1;
}
ydirection *= -1;
}
//COLOR
float red = map(xpos,0, width, 0, 500);
float blue = map(ypos, 0, width, 0, 255);
float green= map(xpos,0,width, 0, 255);
fill(red, green, blue);
// Draw the shape
if (mousePressed == true) {
xpos = xpos - ( xspeed * xdirection ); //this is my problem
ypos = ypos - ( yspeed * ydirection ); //its just stops

} else {
}

}
``````

it’s my first code like that so i think i have some other problem maybe, if u see something wrong pls tell me

I am not sure if I understand, but this is the code, so it just teleports it to the center

``````if (mousePressed == true) {
xpos = width/2;
ypos = height/2; //its just teleports to the center

}
``````

yeah i know this, but i dont need teleport, i need moooooove to the center, like slowly

Consider lerping…
lerp() \ Language (API) \ Processing 3+

Reference states:
`The lerp function is convenient for creating motion along a straight path and for drawing dotted lines.`

`:)`

Another way is to use trigenometry.

First get the angle with atan2(y2-y1,x2-x1);
after it, get the varraible speed (float speed = 5);
after that, set the x amd y speeds by using:

``````float dir = atan2(y2-y1,x2-x1);
float speed = 5;
xspeed = cos(dir)*5;
yspeed = sin(dir)*5;
``````

OMG THANK U IT WORKS
I thought about it all day

1 Like

I usually lerp manually with code but this “helper” function is there to help.

If you want to see what lerp() does it is here:
processing/PApplet.java at master · processing/processing · GitHub

`:)`