I am trying to implement a crouch function without using a pre-made character controller, but it just won’t work. For some reason I have to press ctrl multiple times for my character to either stand up or crouch, and I don’t get why. I tried searching but it seams not many people program this way.
Here’s my code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class move : MonoBehaviour
{
Rigidbody2D rb2d;
SpriteRenderer spriterender;
BoxCollider2D bcol;
bool crouch = false;
[SerializeField]
private LayerMask platformLayerMask;
// Start is called before the first frame update
void Start()
{
rb2d = GetComponent<Rigidbody2D>();
spriterender = GetComponent<SpriteRenderer>();
bcol = GetComponent<BoxCollider2D>();
}
// Update is called once per frame
void FixedUpdate()
{
if (crouch == true)
{
bcol.enabled = false;
}
else if (crouch == false) { bcol.enabled = true; }
if (Input.GetKey("d") || Input.GetKey("right"))
{
rb2d.velocity = new Vector2(4, rb2d.velocity.y);
spriterender.flipX = false;
}
////////
else if (Input.GetKey("a") || Input.GetKey("left"))
{
rb2d.velocity = new Vector2(-4, rb2d.velocity.y);
spriterender.flipX = true;
}
////////
else
{
rb2d.velocity = new Vector2(0, rb2d.velocity.y);
}
////////
if (IsGrounded() && Input.GetKey("space") || Input.GetKey("up") && IsGrounded())
{
rb2d.velocity = new Vector2(rb2d.velocity.x, 17);
}
if (Input.GetKeyDown(KeyCode.LeftControl))
{
crouch = true;
rb2d.velocity = new Vector2((rb2d.velocity.x) / 2, (rb2d.velocity.y) - 5);
Debug.Log("crouching");
}
if (Input.GetKeyUp(KeyCode.LeftControl))
{
crouch = false;
rb2d.velocity = new Vector2(rb2d.velocity.x, rb2d.velocity.y);
Debug.Log("standing");
}
}
////////////////
private bool IsGrounded()
{
RaycastHit2D raycastHit = Physics2D.BoxCast(bcol.bounds.center, bcol.bounds.size, 0f, Vector2.down, 1f, platformLayerMask);
Color rayColor;
if (raycastHit.collider != null)
{
rayColor = Color.green;
}
else
{
rayColor = Color.red;
}
Debug.DrawRay(bcol.bounds.center + new Vector3(bcol.bounds.extents.x, 0), Vector2.down * (bcol.bounds.extents.y + 1f), rayColor);
Debug.DrawRay(bcol.bounds.center - new Vector3(bcol.bounds.extents.x, 0), Vector2.down * (bcol.bounds.extents.y + 1f), rayColor);
Debug.DrawRay(bcol.bounds.center - new Vector3(bcol.bounds.extents.x, bcol.bounds.extents.y, 1f), Vector2.right * (bcol.bounds.extents.y), rayColor);
return raycastHit.collider != null;
}
}
Small update: Today I tried the same code, and the first time it worked, but then it stopped working for some reason
– Kaizara