- Home /
How can I define two-dimensional curves? (like: circle)
Hi fellow Unity devs,
I'm looking for a way to define two-dimensional enemy movement in my game and I really like the animation curve fields. However, it'd be extremely hard for me to define all sorts of nice loops different kinds of enemies could move along using two separate curve editors. Is there a way I could define curves on two (X/Y) dimensions in one single editor? The simplest example is a circle. That's a separate SIN and a COS on X/Y respectively.
Thank you.
Hi, using splines could be a solution, check the asset store. It's also not so difficult to implement as a game and editor extension.
Thanks dns. I'm looking at this tutorial: http://www.habrador.com/labs/catmull-rom-splines/ I was looking for a built-in field type that the inspector would recognize, but if there's no better option, I'll think about adopting the approach seen in the tutorial.
Answer by cjdev · Aug 19, 2015 at 07:43 PM
For my own uses I found Bezier curves to be the easiest to work with. Quadratic Bezier curves are the simplest as they use only one control point. Basically how they work is you pick a starting and end point and a control point which determines the direction the curve bends out towards. See this picture for an example:
You input the three points, v0 (starting point), v1 (control point), and v2 (ending point), as well as a time t between 0 - 1 which determines where along the curve you are as a percentage. The equation and code implementation for this is actually very easy and you can see a function here that returns a point on the curve at time t give your three points:
public Vector2 CalcBezier(Vector2 p0, Vector2 p1, Vector2 p2, float t)
{
return new Vector2((1 - t) * (1 - t) * p0.x + 2 * (1 - t) * t * p1.x + t * t * p2.x,
(1 - t) * (1 - t) * p0.y + 2 * (1 - t) * t * p1.y + t * t * p2.y);
}
Thanks djdev, this is great advice. I think it'd be workable for my needs. The only thing is that I'll still need to create an editor solution for this (either a custom inspector or a game object based one as shown in the tutorial I linked), but this seems inevitable, so there's no point keeping this question open. Accepted.