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!
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()