How to Make path curves in Godot 3d using code?

Curves are nothing but mathematical equations. As the curve becomes complex so does the equation. Game developers need not understand the maths behind drawing curves but the function is what is needed. In this tutorial we will see how to draw Bezier curve in Godot with code.

There are two types of Bizier curves we will see in this tutorial

  1. Cubic Bezier
  2. Quadratic Bezier

Let’s see how to use them

Both Cubic Bezier and quadratic Bezier use interpolation from first point to the next to draw a curve. The only difference is quadratic Bezier requires minimum 3 points and cubic Bezier requires minimum 4 points.

Free Unity asset banner

Your Bizer curve function looks like this where p0,p1,p2,p3 are vector 2 points in space. This function returns a point on the Bizier curve.

func _cubic_bezier(p0: Vector2, p1: Vector2, p2: Vector2, p3: Vector2, t: float):
	var q0 = p0.linear_interpolate(p1, t)
	var q1 = p1.linear_interpolate(p2, t)
	var q2 = p2.linear_interpolate(p3, t)
	var r0 = q0.linear_interpolate(q1, t)
	var r1 = q1.linear_interpolate(q2, t)
	var s = r0.linear_interpolate(r1, t)
	return s

To use this to move an object along the curve, you need to increase the value of t from 0 to 1. If you keep increasing t the curve will overshoot in the direction of the last point.

func _process(delta):
	if t<1:
		t += speed * delta
		print(_cubic_bezier(p0, p1, p2, p3, t))
		position = _cubic_bezier(p0, p1, p2, p3, t)

Here is the complete code

extends Sprite


var p0=Vector2(0,0)
var p1=Vector2(0,-100)
var p2=Vector2(100,-100)
var p3=Vector2(-100,-150)
var t = 0
var speed=1

func _cubic_bezier(p0: Vector2, p1: Vector2, p2: Vector2, p3: Vector2, t: float):
	var q0 = p0.linear_interpolate(p1, t)
	var q1 = p1.linear_interpolate(p2, t)
	var q2 = p2.linear_interpolate(p3, t)
	var r0 = q0.linear_interpolate(q1, t)
	var r1 = q1.linear_interpolate(q2, t)
	var s = r0.linear_interpolate(r1, t)
	return s

func _process(delta):
	if t<1:
		t += speed * delta
		position = _cubic_bezier(p0, p1, p2, p3, t)

This code will work in 3D with some changes. You need to pass vector 3 in place of vector 2.

In case you want to use a quadratic Bezier. Here is the code for that

extends Sprite


var p0=Vector2(0,0)
var p1=Vector2(0,-100)
var p2=Vector2(100,-100)
var p3=Vector2(-100,-150)
var t = 0
var speed=1

func _quadratic_bezier(p0: Vector2, p1: Vector2, p2: Vector2, t: float):
	var q0 = p0.linear_interpolate(p1, t)
	var q1 = p1.linear_interpolate(p2, t)	
	
	var s = q0.linear_interpolate(q1, t)
	return s

func _process(delta):
	if t<1:
		t += speed * delta
		position = _quadratic(p0, p1, p2, t)

Hope you were able to move your object using code. If you need any help, leave it in the comment box below.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.