Switching inertia angle based on rotation direction around a point

I am making a rope swinging game using constraints, and to stabilize the player while they swing, I am using a bodyGyro with the CFrame of the player’s velocity.

( Basically, the gyro faces the player towards where they are flying/falling. )

Right now, I am using this code to set the gyro.

Gyro.CFrame = DirectionVector * CFrame.Angles(0,0,( math.rad(180) + inertiaAngle ))

DirectionVector is the CFrame of the players velocity direction, while inertiaAngle is the angle.

Right now, the plus sign after math.rad(180) is determining which direction this code works, which right now, is clockwise. If it were minus, it would work counter-clockwise.

The code working correctly clockwise.

10 PM

The angle being the opposite of what it should be going counter-clockwise.

41 PM

My question is, is there a way to set up the math so that it is able to work regardless of direction, without using an if-statement or something?

1 Like

Yes, using vectors.

Given two axis, you can construct a CFrame. It looks like you want “up” for the character to be toward the other end of the rope, and “forward” I’ll assume you want to face downward again towards the other end of the rope. Given the character’s current position and the position at the other end of the rope, here is how you can construct that CFrame:

local down = Vector3.new(0, -1, 0)
local function getCFrame(humanoidPos, ropePos)
    local up = (ropePos - humanoidPos).Unit
    local forward = down
    local left = up:Cross(down)
    forward = left:Cross(up)
    return CFrame.fromMatrix(
        humanoidPos,
        left, up, forward
    )
end

It uses the cross product to find the left vector orthogonal to straight down and towards the other end of the line. Finally since we are in three dimensions, given two orthogonal axis we can solve for the only other possible direction orthogonal to the first two axis. This is our “forward” 90 degrees to the “up” and “left” and somewhere between straight down in world space and our local “up”.

Just pass this CFrame to the Gyro.

3 Likes