- Home /
How to prevent movement in a specific direction only?
I have a trigger box and when the player is in this trigger I would like to prevent their movement in a specific direction. For example they can move forward, backward and left but not right. I have previously controlled movement along a specific axis by setting the rigidbody.velocity.x/rigidbody.velocity.z to zero; however in this case I do not want the entire axis movement stopped, only in a specific direction. Since I am using a rigidbody/capsule collider setup, I have tried experimenting with the position constraints however these do not completely stop the player from moving. What is an effective way to do this?
Here is the code that I am using:
//Cover Left Stop Movement
if (Input.GetButton("Left") && inCoverLeft) {
stopMovement = true;
}
else {
stopMovement = false;
}
//Cover Right Stop Movement
if (Input.GetButton("Right") && inCoverRight) {
stopMovement = true;
}
else {
stopMovement = false;
}
While the player stays in a left or right trigger the relevant boolean (inCoverLeft or inCoverRight) is set to true. I then check in update for when the boolean is true and either the left or right arrow is being pressed. If both the relevant boolean and the corresponding arrow are "true" I set another boolean (stopMovement) to true which is checked for when applying movement physics to the player. Now, while this does stop the player initially, the problem is that once stopped if you continue to quickly tap the arrow key it slowly but surely nudges the player inside the trigger. This is because the movement is stopped only when the key is being held and therefore in the split second before the stopMovement boolean is set to true, the psychics movement gives the player a small nudge each time.
Your answer
Follow this Question
Related Questions
Stop object movement in 1 direction along axis 1 Answer
Enemy AI Movement one axis at a time (8 directional - 2.5d) towards player/target 2 Answers
Freeze Character control on axis 0 Answers
freeze an object for a while or reset value or reverse it? 2 Answers
Why does my character only dash forward and not in the moving direction? 1 Answer