- Home /
Crouch enabled on certain areas?
I want my player only to crouch on certain areas, invisible triggers with the tag "crouchArea". They cannot enter this areas in walking or running mode, only in crouching mode. How can I achieved this?
This is the code for crouching in the player movement script:
if(Input.GetKey("c")) {
h = 0.5 * height;
speed = crouchSpeed;
}
Thanks!
Answer by Chronos-L · Mar 26, 2013 at 11:25 AM
If you want player to stay crouched in crouchArea even if the "C" key is not pressed, in another word, forced crouching (perhaps your player is in an airduct or something like that).
Partial Player Script (C#)
private bool isCrouching = false;
private bool isInCrouchArea = false;
void Update() {
...
//Either pressing C or currently in crouch area will make us crouch
isCrouching = Input.GetKey("c") || isInCrouchArea;
if(isCrouching) {
h = ...
speed = ...
}
}
void OnCollisionEnter( Collision other ) {
if( other.gameObject.tag == "crouchArea" && isCrouching ) {
Physics.IgnoreCollision( other.collider, collider );
isInCrouchArea = true;
}
}
void OnCollisionExit( Collision other ) {
if( other.gameObject.tag == "crouchArea" ) {
Physics.IgnoreCollision( other.collider, collider, false );
isInCrouchArea = false;
}
}
Partial Player Script (JS)
private var isCrouching : boolean = false;
private var isInCrouchArea : boolean = false;
function Update() {
...
//Either pressing C or currently in crouch area will make us crouch
isCrouching = Input.GetKey("c") || isInCrouchArea;
if(isCrouching) {
h = ...
speed = ...
}
}
function OnCollisionEnter( other : Collision ) {
if( other.gameObject.tag == "crouchArea" && isCrouching ) {
Physics.IgnoreCollision( other.collider, collider );
isInCrouchArea = true;
}
}
function OnCollisionExit( other : Collision ) {
if( other.gameObject.tag == "crouchArea" ) {
Physics.IgnoreCollision( other.collider, collider, false );
isInCrouchArea = false;
}
}
I am making the crouchArea a normal collider instead of a trigger, somehow it feels like that it is a bit more secure than a trigger; anything can move pass a trigger, but only a collider that isCrouching
will be able to move through the collider by Physics.IgnoreCollision()
You can always switch back to using a trigger if you want to; just change to OnTrigger*()
and remove the Physics.IgnoreCollision()
Code is not tested and it is been a while since I wrote in uJS. You will have to figure it out yourself if there are any syntax errors. I am quite sure that the logic is okay though.
Your answer
![](https://koobas.hobune.stream/wayback/20220613095119im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Player movement 0 Answers
Circular movement of the player 0 Answers
Player movement for iOS? 1 Answer
can anyone find the issue with this code? 2 Answers
Multiple Camera Angles, Choseable 1 Answer