简化 Lua 中的 "LookAt" 函数

大家好!

我有一个名为 "LookAt" 的 Lua 函数正在工作中。

代码和逻辑没有错误。

但我相信我们可以简化数学逻辑。

function LookAt(target)
  local origin = Vec3.New(Engine.ClientData.Origin)
  local direction = origin - target

  Engine.Pitch = math.deg(math.atan(direction.Z, math.sqrt((direction.X ^ 2) + (direction.Y ^ 2))))
  Engine.Yaw = math.deg(math.atan(direction.Y, direction.X)) - 180.0
end
点赞
用户1108505
用户1108505

我认为不太可能简化数学逻辑。这里几乎没有可以利用的冗余。但你可以按照以下方式将它分解:

function atan_deg(y, x)
  return (math.deg(math.atan(y, x)))
end

function hypotenuse(x, y)
  return (math.sqrt(x^2 + y^2))
end

function LookAt(target)
  local origin = Vec3.New(Engine.ClientData.Origin)
  local direction = origin - target
  local X, Y, Z = direction.X, direction.Y, direction.Z

  Engine.Pitch = atan_deg(Z, hypotenuse(X, Y))
  Engine.Yaw = atan_deg(Y, X) - 180.0
end
2017-10-12 19:21:44