So I would need to find a way to multiply the determined X and Z axis for it to add up to the original Magnitude. But I’m currently clueless on how to do this.
Correct me if I’m wrong, but I believe :Cross() finds a perpendicular vector to the inputed vectors, in which the output vector does not cater for my desire as it finds a sign value and an entirely different vector.
Can you explain why you want to do this? That would help with coming up with an answer.
You want to tilt or rotate the vector away from the Y-axis, maintaining length, until it’s tip lies below a certain threshold? Is that an accurate wording of your question?
We know |v| and |AB|, and together with AE those form a right angle triangle so we can use Pythagoras’ thing: |AE| = sqrt(|v|^2 + |AB|^2). |AE| is the length of the horizontal component of the result vector. The vertical component is just maxY or minY (A.y = |AB| in the illustration).
function clampYMaintainMagnitude(v: Vector3, minY: number, maxY: number): Vector3
--Vertical component
local dirY = Vector3.new(0, 1, 0)
local clampedLenY = math.clamp(v.Y, minY, maxY)
if clampedLenY == v.Y then return v end
--Horizontal component
local dirXZ = v * Vector3.new(1, 0, 1) --Component-wise multiplication like this "sets the Y component to 0"
local lenXZ = math.sqrt(math.pow(v.Magnitude, 2), math.pow(clampedLenY, 2))
return dirY * clampedLenY + dirXZ * lenXZ
end
I can’t test the code right now so let me know if it doesn’t behave as expected
Whoops yeah you’re right about all that. Here’s a fixed version:
function clampYMaintainMagnitude(v: Vector3, minY: number, maxY: number): Vector3
--Vertical component
local dirY = Vector3.new(0, 1, 0)
local clampedLenY = math.clamp(v.Y, minY, maxY)
if clampedLenY == v.Y then return v end
--Horizontal component
local dirXZ = (v * Vector3.new(1, 0, 1)).Unit --Component-wise multiplication like this "sets the Y component to 0"
local lenXZ = math.sqrt((v.Magnitude * v.Magnitude) - (clampedLenY * clampedLenY))
return dirY * clampedLenY + dirXZ * lenXZ
end
I also changed it to not use math.pow, although that’s not strictly wrong. Hope this works, still can’t test it
Just a minor nitpick, the magnitude is a bit inaccurate as it’s supposed to be 1 (I’m getting minor discrepancies in 0.1 - 0.2). Could this be attributed to the fact that we cant calculate the X and the Z horizontal segment individually ? I’m still unsure.
Your calculation works perfectly fine besides that minor issue though.