2D Lua - 子弹速度不正确且无法预测。

我使用了从互联网上收集的各种方法来让这个程序运行,但是子弹似乎随机飞出。我尝试在一些变量前加负号并改变三角函数,但没有用。我尝试使用玩家手臂的旋转,因为它可以准确指向用户的鼠标,但是无法提高精度。我尝试确定子弹是否遵循某种模式,就像我需要为手臂反转Y变量一样,但我在这里找不到任何模式。看下面这段代码我在每次射击子弹时记录了一些信息,但这并没有对问题有所帮助。

local x, y = objects.PlayerArm:GetPos()
local bullet = createBullet( x + objects.Player:GetWide(), y )

local mX, mY = gui.MouseX(), gui.MouseY()
local shootAngle = math.atan2((mY - y), (mX - x))
shootAngle = math.deg( math.Clamp(shootAngle, -90, 90) )
--shootAngle = objects.PlayerArm.Rotation

bullet.VelocityX = math.cos(shootAngle) * 5
bullet.VelocityY = math.sin(shootAngle) * 5
--bullet.Rotation = shootAngle
print("Angle", shootAngle, "Velocity X and Y", bullet.VelocityX, bullet.VelocityY)

在控制台打印了以下信息。

角度 47.920721521 速度 X 和 Y -3.4948799788437 -3.5757256513158

角度 24.928474135461 速度 X 和 Y 4.8960495864893 -1.0142477244922

角度 16.837472625676 速度 X 和 Y -2.1355174970471 -4.5210137159497

角度 10.684912400003 速度 X 和 Y -1.5284445365972 -4.7606572338855

角度 -1.029154804306 速度 X 和 Y 2.5777162320797 -4.2843178018061

角度 -11.63363399894 速度 X 和 Y 2.978190104641 4.0162648942293

角度 -22.671343621981 速度 X 和 Y -3.8872502993046 3.1447233758403

http://i.gyazo.com/e8ed605098a91bd450b10fda7d484975.png

点赞
用户2726734
用户2726734

正如 @iamnotmaynard 怀疑的那样,Lua 使用 C 的数学库,因此所有三角函数都使用弧度而不是角度。最好将所有角度存储在弧度中,并仅在需要更友好的格式时将其打印成角度。否则,在每次使用角度时都需要进行许多弧度和角度之间的转换。下面的代码已更新为仅使用弧度并以角度打印。

local mX, mY = gui.MouseX(), gui.MouseY()
local shootAngle = math.atan2((mY - y), (mX - x))
shootAngle = math.max(-math.pi/2, math.min(shootAngle, math.pi/2))
bullet.VelocityX = math.cos(shootAngle) * 5
bullet.VelocityY = math.sin(shootAngle) * 5
print("Angle (radians)", shootAngle, "(degrees)", math.deg(shootAngle),
        "Velocity X and Y", bullet.VelocityX, bullet.VelocityY)

然而,计算 x 和 y 方向的速度根本不需要使用角度。下面的函数仅使用位移计算 VelocityX 和 VelocityY,并确保速度仅在右下和右上象限中。

function shoot(x, y, dirx, diry, vel)
   local dx = math.max(dirx - x, 0)
   local dy = diry - y
   local sdist = dx * dx + dy * dy
   if sdist > 0 then
     local m = vel / math.sqrt(sdist)
     return dx * m, dy * m
   end
end

bullet.VelocityX, bullet.VeclocityY = shoot(x, y, gui.MouseX(), gui.MouseY(), 5)
2015-01-04 19:29:59