Hello, first sorry for my bad English, i’m a French speaker.
I’m a making a 2d game, and i want to move a pawn from a hole A to another B with a circular or elliptique movement, but the result was disappointing. I found the bezier curve on Wikepedia, but i don’t know how to implement that in C#. Someone could help me please. I found the explanation here : http://en.wikipedia.org/wiki/B%C3%A9zier_curve#Constructing_B.C3.A9zier_curves
To get the point at position t (where t is 0->1) on a bezier of 3 points A,B,C you first lerp t from A to B, then lerp t from B to C, then lerp t from AB to BC.
var a = new Vector2(0,0);
var b = new Vector2(1,0);
var c = new Vector2(1,1);
float t = 0.5f; //lets get halfway down the curve
var ab = Vector2.Lerp(a,b,t);
var bc = Vector2.Lerp(b,c,t);
var result = Vector2.Lerp(ab,bc,t);
As a reusable function:
public Vector2 Bezier(float t, Vector2 a, Vector2 b, Vector2 c)
{
var ab = Vector2.Lerp(a,b,t);
var bc = Vector2.Lerp(b,c,t);
return Vector2.Lerp(ab,bc,t);
}
For instance, if you had some start time, and a duration, you could say:
var t = (Time.time - startTime) / duration;
Vector2 position;
if(t < 1.0f)
position = Bezier(t, point1, point2, point3);
else
position = point3; //1 or larger means we reached the end
I got this js script in the wiki of unity but the script draw me a bezier curve on screen. How i can modify the script and instead of draw a curve, i move my object ? I know that i have to delete the lineRender but where sould i change my translate.position ?
@script ExecuteInEditMode()
#pragma strict
public var start : GameObject;
public var middle : GameObject;
public var end : GameObject;
public var color : Color = Color.white;
public var width : float = 0.2;
public var numberOfPoints : int = 20;
function Start()
{
// initialize line renderer component
var lineRenderer : LineRenderer =
GetComponent(LineRenderer);
if (null == lineRenderer)
{
gameObject.AddComponent(LineRenderer);
}
lineRenderer = GetComponent(LineRenderer);
lineRenderer.useWorldSpace = true;
lineRenderer.material = new Material(
Shader.Find("Particles/Additive"));
}
function Update()
{
// check parameters and components
var lineRenderer : LineRenderer =
GetComponent(LineRenderer);
if (null == lineRenderer || null == start
|| null == middle || null == end)
{
return; // no points specified
}
// update line renderer
lineRenderer.SetColors(color, color);
lineRenderer.SetWidth(width, width);
if (numberOfPoints > 0)
{
lineRenderer.SetVertexCount(numberOfPoints);
}
// set points of quadratic Bezier curve
var p0 : Vector3 = start.transform.position;
var p1 : Vector3 = middle.transform.position;
var p2 : Vector3 = end.transform.position;
var t : float;
var position : Vector3;
for(var i : int = 0; i < numberOfPoints; i++)
{
t = i / (numberOfPoints - 1.0);
position = (1.0 - t) * (1.0 - t) * p0
+ 2.0 * (1.0 - t) * t * p1
+ t * t * p2;
lineRenderer.SetPosition(i, position);
}
}