I’m looking for a way to create a circular motion for an object. I got the linear and wave (sin) motions working fine. I pretty much know their equations, and they’re actual functions (for each point of the graph in x, there’s one and only one corresponding point in y - which is the definition of a function) - But the circle isn’t a function, since foreach point in the graph, there are two corresponding y values.
From my dusty math knowledge, the equation of the circle is:
x^2 + y^2 = r;
How to get this formula to work in code?
What I have is, an abstract Movement class, that other types of movements inherit from, and override the method GetY - so LinearMovement’s GetY just returns the the y value of the velocity, etc. Here’s the virtual moving method in the abstract Movement
protected virtual void Move()
{
velocity.y = GetY();
cachedTransform.localPosition += (velocity + direction) * Time.deltaTime * speed;
// more unrelated stuff
}
GetY for the sine movement:
protected override float GetY()
{
return Mathf.Sin(2 * Mathf.PI * Time.time * frequency) * wavelength;
}
GetY for the linear movement:
protected override float GetY()
{
return velocity.y;
}
Now, what I tried to do for my circular movement, is return:
sqrt(r - x * x);
But it didn’t give me the right movement.
Please don’t give answers related to any of the rotation methods (transform.Rotate, transform.RotateAround, etc) - cause that’s not the point of this question.
Thanks for any tips.
EDIT:
if you’re curious where I get direction from:
protected virtual void InitDirection()
{
// just get some random orientation for the point/object to face to start moving
float randZ = Random.Range(minInitialOrientation, maxInitialOrientation);
direction = Quaternion.Euler(0, 0, randZ) * cachedTransform.right;
}