Hi everyone, I’m a beginner on coding. So, I was trying to make my player to crouch but somehow the script seems to not work. Any idea what is the probable cause?
For the context, for movement of the character such as moving using W,A,S,D and jumping, I’m using the tutorial from brackeys.
Brackeys tutorial =>
Here is the code that I use for the movement (without the crouch)
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
public CharacterController controller;
public float speed = 12f;
public float gravity = -9.81f;
public float jumpHeight = 3f;
public Transform groundCheck;
public float groundDistance = 0.4f;
public LayerMask groundMask;
Vector3 velocity;
bool isGrounded;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
isGrounded = Physics.CheckSphere(groundCheck.position, groundDistance, groundMask);
if(isGrounded && velocity.y < 0)
{
velocity.y = -2f;
}
float x = Input.GetAxis("Horizontal");
float z = Input.GetAxis("Vertical");
Vector3 move = transform.right * x + transform.forward * z;
controller.Move(move * speed * Time.deltaTime);
if(Input.GetButtonDown("Jump") && isGrounded)
{
velocity.y = Mathf.Sqrt(jumpHeight * -2f * gravity);
}
velocity.y += gravity * Time.deltaTime;
controller.Move(velocity * Time.deltaTime);
}
}
For crouching I use another tutorial =>
Which the code that I use is
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Crouch : MonoBehaviour
{
public CharacterController playerController;
public float crouchSpeed, normalHeight, crouchHeight;
public Vector3 offset;
public Transform player;
bool crouching;
void update()
{
if(Input.GetKeyDown(KeyCode.LeftControl))
{
Debug.Log("Crouch Triggered");
crouching = !crouching;
}
if(crouching == true)
{
playerController.height = playerController.height - crouchSpeed * Time.deltaTime;
if(playerController.height <= crouchHeight)
{
playerController.height = crouchHeight;
}
}
if(crouching == false)
{
playerController.height = playerController.height + crouchSpeed * Time.deltaTime;
if(playerController.height < normalHeight)
{
player.position = player.position + offset * Time.deltaTime;
}
if(playerController.height >= normalHeight)
{
playerController.height = normalHeight;
}
}
}
}
are there any conflicting codes that are causing it not to work? Thanks ![]()