Limiting player movement with clamp on rotated movement

Hi everyone. I’m trying to limit player movement on x axis with clamp values but I have a problem. I am using transform.position and when I clamp my x value everything works fine. But my game has turning points which player rotates left or right and keeps moving in the rotated axis multiple times in a scene. So my x position is changing after rotations and movement. My question is how can I limit movement on x and not mess up my clamp after rotations and position changes.

You can use max and min clamps like transform.position.x +5 and transform.position.x-5

Alright, I see your inspiration, and clamping the movement values will never work, and if it does, it will be such a hacky solution and incredibly flawed. Instead, add colliders on the side of the floors, so that the if the player does try to go off them, the player will just hit a collider. This should work. You will have to do some tweaking with the placement and rotation of the colliders but I did something similar for a game of mine, and with enough development, it should work.

However, if you are still really wanting to do the other solution (Clamping solution), I can write up some pseudocode.

// Here insert logic for isRunningOnXAxis and isRunningOnZAxis and isTurning. which are all booleans
// isRunningOnXAxis just says whether the player is running forward on the xAxis
// (this will change because of the turns)
// isRunningOnZAxis is the same thing as isRunningOnXAxis, but for the Zed axis
// isTurning is a boolean on whether the player is turning this frame

// Define clampValue which is a class variable of type float

if (isRunningOnZAxis && isTurning){
    clampValue = transform.position.z;
}
if (isRunningOnXAxis && isTurning){
    clampValue = transform.position.x;
}

transform.position = new Vector3(
     isRunningOnXAxis ? Mathf.Clamp(transform.position.x, clampValue - 5, clampValue + 5 : transform.position.x,
    transform.position.y,
    isRunningOnZAxis ? Mathf.Clamp(transform.position.z, clampValue - 5, clampValue + 5 : transform.position.z,
);

I am not 100% sure this will work, but it should give you some idea on a solution.

Hey @UnityPlum thanks for the answer. My game has all the colliders in borders and I have been using rb.velocity at first. But slide touch was not really smooth while using the rb.velocity so I thought it needed a change. I changed movement to transform.position with clamp.I will try the code you shared but do you have an approach on which movement method to use working with colliders and also provides smooth movement?