## Friday, 30 May 2014

### Prototyping Smooth Curves - Quadratic Bézier Curves

Often, you need smooth curves in your game. One of the popular solutions is implementing cubic Bézier curves. Cubic curves let you feel like there are two points in control of the curve.

 Cubic Bézier Curve
For an artist who avoids coding, cubic curves provide a great feel of what the end result will look like. In case you're building a tool for artists, you better provide them with those curves. However, for prototyping, what I end up using a lot is quadratic curves. They're very intuitive to include in your code.
 Quadratic Bézier Curves
They're intuitive because every angle formed by those points (e.g. P0P1, and P2 in the figure above) represents a bend in the curve. It feels like you're drawing the same curve, but with edges.

 Intutive use of Quadratic Curves

Actually, that is why I started this blog post. Just to tell you how intutive they are. Ok! I'll write a little on how to use them, but allow me to do some copying from Wikipedia.

A quadratic Bézier curve is the path traced by the function B(t), given points P0P1, and P2,
${\displaystyle \mathbf {B} (t)=(1-t)[(1-t)\mathbf {P} _{0}+t\mathbf {P} _{1}]+t[(1-t)\mathbf {P} _{1}+t\mathbf {P} _{2}]{\mbox{ , }}0\leq t\leq 1}$,

If you happened to use Unity, then P0P1, and P2  could be represented using Vector3 or Vector2. In Unity, Vector3 or Vector2 can be multiplied by a scalar ( ). could be a float variable from 0 to 1. = 0 gives the first point P0 (first point in the curve segment). = 1 gives the last point P(last point in the curve segment).
I guess that is all you need to get started. Any point on the curve (the red curve in the figure above) can be calculated given a t (notice = 0.50 in the figure above) and a 3 points ( P0, P1, and P2 in the figure above).

void Curve (float t, Vector2 P0,Vector2 P1,Vector2 P2)
{
return (1-t)*( (1-t)*P0 + t*P1 ) + t*( (1-t)*P1 + t*P2 );
}

Well, this is just one segment. How do you add more segments? You need to build a datastructure that could capture those multiple segments. There are many examples that have good Bézier implementation. Pick any one you like, it doesn't matter what kind of Bézier curves is being used (Quadratic or Cubic). They have a lot of similar ideas. For example, check out this tutorial.