【问题标题】:2D Lua - Bullet velocity is not correct nor predictable2D Lua - 子弹速度不正确也不可预测
【发布时间】:2015-01-04 17:29:57
【问题描述】:

我正在使用我从互联网上的各种方法收集的一些东西来完成这项工作,但我的子弹似乎朝随机的方向飞去。我试过在东西前面扔负面迹象并切换触发器,但无济于事。我尝试过使用玩家手臂的旋转,因为它准确地指向了用户的鼠标,但没有给我更多的准确性。

我试图确定子弹是否遵循我需要为我的手臂反转 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

【问题讨论】:

  • 你需要用弧度代替度数吗?
  • 天哪,非常感谢。我将 shootAngle 保留为弧度并将 math.sin(shootAngle) 更改为 math.sin(-shootAngle) 并修复了它。

标签: math lua rotation 2d bullet


【解决方案1】:

正如@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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-30
    • 2018-10-01
    • 1970-01-01
    • 2017-10-12
    • 2021-09-26
    相关资源
    最近更新 更多