- Home /
Help with crouch button (MOBILE CONTROL)
[I'm sorry if my text has errors, I can't speak English]
I've been trying to adapt Unity's standard ThirdPersonController to a virtual controller, so I added another script and made some changes to the script that was already assigned to it. The skip button and the joystick worked, only the crouch button don't worked properly.
When I press the button, the character crouches, but cannot enter smaller areas. Here are how pictures of the problem:
(but it should fit, as the capsule responds to the script's command). In short, the virtual button does exactly what the "C" key does, but the character does not recognize the command, it is as if he were still standing.
If anyone can help me, I appreciate it. But simplify the explanation, because I don't know how to program. : ((
Here are the script lines of the character itself (ThirdPersonCharacter)
void ScaleCapsuleForCrouching(bool crouch)
{
if (m_IsGrounded && crouch)
{
if (m_Crouching) return;
m_Capsule.height = m_Capsule.height / 2f;
m_Capsule.center = m_Capsule.center / 2f;
m_Crouching = true;
}
else
{
Ray crouchRay = new Ray(m_Rigidbody.position + Vector3.up * m_Capsule.radius * k_Half, Vector3.up);
float crouchRayLength = m_CapsuleHeight - m_Capsule.radius * k_Half;
if (Physics.SphereCast(crouchRay, m_Capsule.radius * k_Half, crouchRayLength, Physics.AllLayers, QueryTriggerInteraction.Ignore))
{
m_Crouching = true;
return;
}
m_Capsule.height = m_CapsuleHeight;
m_Capsule.center = m_CapsuleCenter;
m_Crouching = false;
}
}
void PreventStandingInLowHeadroom()
{
// prevent standing up in crouch-only zones
if (!m_Crouching)
{
Ray crouchRay = new Ray(m_Rigidbody.position + Vector3.up * m_Capsule.radius * k_Half, Vector3.up);
float crouchRayLength = m_CapsuleHeight - m_Capsule.radius * k_Half;
if (Physics.SphereCast(crouchRay, m_Capsule.radius * k_Half, crouchRayLength, Physics.AllLayers, QueryTriggerInteraction.Ignore))
{
m_Crouching = true;
}
}
}
the other script that was added (OwnThirdPersonController)
private void Crouch()
{
var crouchbutton = CrouchButton.Pressed || Input.GetKey(KeyCode.C);
if (!isCrouching && crouchbutton)
{
//crouch
CapCollider.height = 1f;
CapCollider.center = new Vector3(CapCollider.center.x, 0.5f, CapCollider.center.z);
isCrouching = true;
Actions.SetBool("Crouch", isCrouching);
}
Debug.DrawRay(transform.position, Vector3.up * 2f, Color.green);
if (isCrouching && !crouchbutton) return;
{
//try to stand up
Ray crouchRay = new Ray(Rigidbody.position + Vector3.up * CapCollider.radius * Cooldown, Vector3.up);
float crouchRayLength = CapCollider.height - CapCollider.radius * Cooldown;
if (Physics.SphereCast(crouchRay, CapCollider.radius * Cooldown, crouchRayLength, Physics.AllLayers, QueryTriggerInteraction.Ignore))
{
isCrouching = true;
return;
}
CapCollider.height = CapCollider.height;
CapCollider.center = CapCollider.center;
isCrouching = false;
}
}