I'm trying to add crouching to my first-person game. Since no animation needed I thought the simpler way to achieve crouching is by decreasing the player's height and making the player move slower. I'm trying to achieve this using the new input system. Here is my attempt:
[SerializeField] float walkSpeed = 10f;
[SerializeField] float runSpeed = 25f;
[SerializeField] float crouchSpeed = 5f;
[SerializeField] CharacterController controller;
public bool crawl;
private void Update()
{
if (crawl)
{
Crouching();
}
else
{
StandingUp();
}
}
private void Crouching()
{
crawl = true;
controller.height = 0.3f;
moveSpeed = crouchSpeed;
}
private void StandingUp()
{
crawl = false;
controller.height = 3f;
moveSpeed = walkSpeed;
}
public void OnCrawl()
{
crawl = true;
}
The input Action part:
[SerializeField] Movement movement;
private void Awake()
{
controls = new PlayerControls();
groundMovement = controls.GroundMovement;
// groundMovement.[action].performed = context => do something
groundMovement.HorizontalMovement.performed = ctx => horizontalInput = ctx.ReadValue<Vector2>();
groundMovement.Crawl.performed = _ => movement.OnCrawl();
}
What is expected is after pressing c, the player gets to a crouching state and when I press c again it should be back up. But it doesn't work. all I get is the button is triggered when it is pressed but nothing really happens.
I had a question before that been answered: How to make character run using the new input system?
but the requirement here is slightly different. unlike in running, here I don't want the user to hold down a key for crouching. I want it to be one click that changes the status from walk to crouch and vice versa.
current result:
when testing the current code, I can see the value crawl
being ticked when I press c
but when I press it again it does not get unticked. and the height of the character does not change as it is supposed to.
CodePudding user response:
This is an optimized solution for this. When pressing the key, it is enough to run the crawl phase change code. The rest of the changes will depend on the movement class.
public bool crawl;
public void CrawlChange()
{
crawl = !crawl;
if (crawl)
{
controller.height = 0.3f;
moveSpeed = crouchSpeed;
}
else
{
controller.height = 3f;
moveSpeed = walkSpeed;
}
}
From the control code, call this code by pressing the special crawl key. Also, this coordination does not need to be in the Update to prevent unnecessary processing in each frame.
groundMovement.Crawl.performed = ctx => movement.CrawlChange(); // switch crawl phase