Friday, June 12, 2015

unity - Moving a 2D object along circular arc between two points


I have a sprite which I need to move along a curve between two points in 2D space. Speed must be consistent all the way. No physics involved. How can I achieve this? enter image description here


The object is sun sprite.


enter image description here



Answer



You can use Bezier Curves.



Given 2 given points, you have to define one third point yourself that controls where the curve is made. In your example you can create the point between your two given points, plus some height.


// Assuming point[0] and point[2] are your starting point and destination
// and all points are Vector3
point[1] = point[0] +(point[2] -point[0])/2 +Vector3.up *5.0f; // Play with 5.0 to change the curve

Then to compute the curve in a script for an object to travel to it, do this:


float count = 0.0f;

void Update() {
if (count < 1.0f) {

count += 1.0f *Time.deltaTime;

Vector3 m1 = Vector3.Lerp( point[0], point[1], count );
Vector3 m2 = Vector3.Lerp( point[1], point[2], count );
myObject.position = Vector3.Lerp(m1, m2, count);
}
}

Basically, to compute a Quadratic Bezier Curve (one with three points) you have to find the interpolated points of it's two lines, construct a line with those two points (The green line in the gif), and interpolate again to find a final point.


enter image description here



As you can see, if you increase the Y value on your second point, the curve will be bigger.


Edit:


If you want to create moving objects like a sun and a moon, create 3 Vector3 points: starting point (where the sun begins travelling) an ending point (where the sun ends up) and a control point (that controls the curve). The control point should be located above the mountains, but the exact value depends on what kind of curve you are looking for.


Now substitute these points with the above example:


point[0] = startingPoint;
point[1] = controlPoint;
point[2] = endingPoint;

I assume that once the sun (or moon) reaches the ending point, they can just disappear from the scene, and re-appear on the next day on the starting point, so it's location until then is irrelevant.


No comments:

Post a Comment

Simple past, Present perfect Past perfect

Can you tell me which form of the following sentences is the correct one please? Imagine two friends discussing the gym... I was in a good s...