接下来我们可以实现一种在2D游戏中常用的算法:贝塞尔曲线(Bezier Curve)。贝塞尔曲线是一种用于绘制平滑曲线的数学工具,广泛应用于计算机图形学、动画、路径规划等领域。
贝塞尔曲线简介
贝塞尔曲线由一组控制点定义,曲线的形状由这些控制点决定。最常见的贝塞尔曲线是二次贝塞尔曲线和三次贝塞尔曲线。
- 二次贝塞尔曲线:由三个控制点 (P_0)、(P_1) 和 (P_2) 定义。
[
B(t) = (1 - t)^2 P_0 + 2(1 - t)t P_1 + t^2 P_2, \quad t \in [0, 1]
]
- 三次贝塞尔曲线:由四个控制点 (P_0)、(P_1)、(P_2) 和 (P_3) 定义。
[
B(t) = (1 - t)^3 P_0 + 3(1 - t)^2 t P_1 + 3(1 - t)t^2 P_2 + t^3 P_3, \quad t \in [0, 1]
]
示例代码
以下是用 Lua 实现的二次和三次贝塞尔曲线:
-- 定义向量结构
Vector = {}
Vector.__index = Vector
function Vector:new(x, y)
local vec = {x = x, y = y}
setmetatable(vec, Vector)
return vec
end
function Vector:scale(scalar)
return Vector:new(self.x * scalar, self.y * scalar)
end
function Vector:add(other)
return Vector:new(self.x + other.x, self.y + other.y)
end
-- 二次贝塞尔曲线
function quadraticBezier(p0, p1, p2, t)
local u = 1 - t
local tt = t * t
local uu = u * u
local p = p0:scale(uu)
p = p:add(p1:scale(2 * u * t))
p = p:add(p2:scale(tt))
return p
end
-- 三次贝塞尔曲线
function cubicBezier(p0, p1, p2, p3, t)
local u = 1 - t
local tt = t * t
local uu = u * u
local ttt = tt * t
local uuu = uu * u
local p = p0:scale(uuu)
p = p:add(p1:scale(3 * uu * t))
p = p:add(p2:scale(3 * u * tt))
p = p:add(p3:scale(ttt))
return p
end
-- 测试贝塞尔曲线
local p0 = Vector:new(0, 0)
local p1 = Vector:new(1, 2)
local p2 = Vector:new(3, 3)
local p3 = Vector:new(4, 0)
print("二次贝塞尔曲线:")
for t = 0, 1, 0.1 do
local point = quadraticBezier(p0, p1, p2, t)
print(string.format("t=%.1f: (%.2f, %.2f)", t, point.x, point.y))
end
print("三次贝塞尔曲线:")
for t = 0, 1, 0.1 do
local point = cubicBezier(p0, p1, p2, p3, t)
print(string.format("t=%.1f: (%.2f, %.2f)", t, point.x, point.y))
end
在这个实现中:
Vector
结构表示一个二维向量,包含基本的向量操作如缩放和加法。
quadraticBezier
函数实现二次贝塞尔曲线,接受三个控制点和参数 (t) 作为输入,返回曲线上对应的点。
cubicBezier
函数实现三次贝塞尔曲线,接受四个控制点和参数 (t) 作为输入,返回曲线上对应的点。
- 测试代码定义了一组控制点,并调用
quadraticBezier
和 cubicBezier
函数计算曲线上不同 (t) 值对应的点,输出结果。
贝塞尔曲线在2D游戏中的路径规划、动画插值、图形绘制等方面有广泛应用。它能够生成平滑的曲线,适用于各种需要平滑过渡的场景。