Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix QuatFromXZDirection for negative dx inputs causing ACUs to spawn the wrong direction #6630

Open
wants to merge 3 commits into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions changelog/snippets/fix.6630.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
- (#6630) Fix ACUs spawned on the right side of the map not facing towards the middle of the map.
4 changes: 2 additions & 2 deletions lua/sim/Unit.lua
Original file line number Diff line number Diff line change
Expand Up @@ -2262,8 +2262,8 @@ Unit = ClassUnit(moho.unit_methods, IntelComponent, VeterancyComponent, DebugUni
---@param self Unit
---@param tpos Vector
RotateTowards = function(self, tpos)
local pos = self:GetPosition()
local dx, dz = tpos[1] - pos[1], tpos[3] - pos[3]
local pX, _, pZ = self:GetPositionXYZ()
local dx, dz = tpos[1] - pX, tpos[3] - pZ
self:SetOrientation(utilities.QuatFromXZDirection(dx, dz), true)
end,

Expand Down
25 changes: 22 additions & 3 deletions lua/utilities.lua
Original file line number Diff line number Diff line change
Expand Up @@ -487,13 +487,32 @@ end
---@param dz number
---@return Quaternion
function QuatFromXZDirection(dx, dz)
-- ang = atan2(dx, dz) -- `dz` is adjacent
-- {0, sin(ang/2), 0, cos(ang/2)}
-- division by zero case
if dx == 0 and dz == 0 then
return UnsafeQuaternion(0, 0, 0, 1)
end

-- q = (0, sin(ang/2), 0, cos(ang/2)) -- definition of our y-axis rotation quaternion we want to get for angle `ang`

-- sin(ang/2) = +/-sqrt((1-cos(ang))/2) -- half angle formula for sin. +/- is sign of sin(ang/2)
-- = +/-sqrt( 0.5 - cos(ang)/2 )
-- = +/-sqrt( 0.5 - a/2h ) -- cos(ang) = adjacent/hypotenuse
-- similar is repeated for cos(ang/2)

local hypot = MathSqrt(dx*dx + dz*dz)
-- use the half-angle formulas
local halfCosA = dz / (2 * hypot)
local sinHalfA = MathSqrt(0.5 - halfCosA)
local cosHalfA = MathSqrt(0.5 + halfCosA)

-- Resolve the +/- part of our result:
-- sign of sin(ang/2) is + for ang in (0, 2pi)
-- sign of cos(ang/2) is + for ang in (0, pi) and - for ang in (pi, 2pi)
-- ang in (pi, 2pi) is when dx is negative, so negate cosHalfA in that case

if dx < 0 then
return UnsafeQuaternion(0, sinHalfA, 0, -cosHalfA)
end

return UnsafeQuaternion(0, sinHalfA, 0, cosHalfA)
end

Expand Down
Loading