Sunday, February 13, 2011

Simple function for a Bezier Curve in C#

The Bezier Curve formula below can be used to define  smooth curves between points in space.

P(t) = (1-t)^3P0 + 3(1-t)^2tP1 + 3(1-t)t^2P2 + t^3P3

The function below is a C# implementation of the formula return the X and Y coordinates for Time (t) given the 4 points that define the Bezier Curve.  You can extend this to 3D very easily.  Include this function in your c# projects to create smooth curves and multi-segment paths.  In a future post I will show how to implement multi-segment paths and circular paths using Bezier Curves.   I used this function and technique in my XNA game projects that required smooth paths for my objects.  I was also able to create a multi-segment curve editor which I will try to cover later on.

C# Code Sample:

        private Vector2 GetPoint(float t, Vector2 p0, Vector2 p1, Vector2 p2, Vector2 p3)
        {
            float cx = 3 * (p1.X - p0.X);
            float cy = 3 * (p1.Y - p0.Y);

            float bx = 3 * (p2.X - p1.X) - cx;
            float by = 3 * (p2.Y - p1.Y) - cy;

            float ax = p3.X - p0.X - cx - bx;
            float ay = p3.Y - p0.Y - cy - by;

            float Cube = t * t * t;
            float Square = t * t;

            float resX = (ax * Cube) + (bx * Square) + (cx * t) + p0.X;
            float resY = (ay * Cube) + (by * Square) + (cy * t) + p0.Y;

            return new Vector2(resX, resY);
        }

To use the function, simply pass in the 4 point and a time (between 0 and 1).   At  t=0 you will be at p0, and at t=1 you will be at p3.      To draw the curve, try calling this function from a for loop that looks something like this:

// preset your p0,p1,p2,p3

Vector2 PlotPoint;
for (float t = 0;  t <= 1.0f; t += 0.01f)
{
  PlotPoint = GetPoint(t, p0, p1, p2, p3);

  // now call some function to plot the PlotPoint
  YourDrawFunction(PlotPoint);
}

2 comments:

  1. Hi, I've hooked your code up in to my game as it was the only one that i could follow and understand. (Hope i'm ok to do this (Credit will be given))

    However, i'm having problems getting something to follow it. I'm using this to make a throwing arce for a grenade. Sorry i can't post any code on here (Don't have it to hand) but any help would really help me out of the rutt i'm currently in.

    Thanks for your help and the code. :)

    ReplyDelete
  2. Hi, good code, but can you complete the example a little more, for examplo, how loading the p0, p1, p2, p3??

    ReplyDelete