I have created a small form of ledge grabbing where the player can jump onto a wall via entering a trigger and then hold onto the ledge and then move sideways while basically dangling from the wall. During the ledge grab the horizontal mouse rotation is clamped to prevent the player from looking too far left or right. But this clamp effect only works on ledge objects that have a rotation of (0,0,0), otherwise my player rotation will “snap” to different directions.
In my scene I have three ledge objects which all share the same tag ‘LedgeObject’ and have both a box collider and rigidbody, and the first ledge has a default rotation of (0,0,0), the second ledge has a default rotation of (0,-90,0), and the third ledge has a default rotation of (0,180,0). When I enter the trigger of the first ledge I have no issues and my code works. However if for example I enter the trigger of the second ledge, my player will immediately rotate from (0,-90,0) to (0,58,0). A similar issue also occurs when entering the trigger of the third ledge object. At the beginning of runtime, my players default rotation is (0,0,0).
public void OnTriggerEnter(Collider other) //LedgeGrab script
{
if (!other.CompareTag("Ledge")) return;
isOnLedge = true;
ledgeObject = other.transform.parent;
}
void Start()
{
// Store the initial x-axis rotation when the script starts
initialXRotation = rotation.x;
}
void Update() // Camera script
{
Vector2 mouse = Input.GetAxis(xAxis) * Vector2.right + Input.GetAxis(yAxis) * Vector2.up;
rotation.x += mouse.x * mouseSens;
rotation.y += mouse.y * mouseSens;
rotation.y = Mathf.Clamp(rotation.y, -90f, 90f);
if (ledgeGrab.isOnLedge) // reference the isOnLedge bool from the LedgeGrab script
{
// Calculate the clamped x-axis rotation based on the initial value
float clampedXRotation = Mathf.Clamp(initialXRotation + rotation.x - initialXRotation, -45f, 45f);
rotation.x = clampedXRotation;
}
var xMouseQuaternion = Quaternion.AngleAxis(rotation.x, Vector3.up);
var yMouseQuaternion = Quaternion.AngleAxis(rotation.y, Vector3.left);
transform.localRotation = yMouseQuaternion;
player.transform.rotation = xMouseQuaternion;
}
I currently try to store the default x-axis rotation and then use that to get my updated rotation so that I can clamp properly based on whichever angle I’m entering the trigger from but it causes even more snapping. I have tried many other methods and debugging has gotten me to this point but no matter how many adjustments I make, only one ledge object will ever clamp properly.