I’m trying to make my first game in Unity: a 3d platformer inspired by the classic Crash Bandicoot games.
I’ve managed to make most of the movement with the character control script below. However, I don’t know how I can do a slide/crouch.
What I want to do is to rotate and move the player down closer to the ground and give him some more speed that decreases over time until he reaches a normal waking state.
I thought about making the player rotate on a specific axis but when he turns the axis doesn’t change so now I’m kind of lost in what to do.
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
public CharacterController controller;
public float speed = 10f;
//turnning smoothness
public float turnSmoothTime = 0.1f;
float turnSmoothVelocity;
//jump controls
public float jumpHeight = 3f;
public float gravity = -29.43f;
Vector3 velocity;
bool isGrounded;
//gravity check
public Transform groundCheck;
public float groundDistance = 0.4f;
public LayerMask groundMask;
// Update is called once per frame
void Update()
{
isGrounded = Physics.CheckSphere(groundCheck.position, groundDistance, groundMask);
if(isGrounded && velocity.y < 0)
{
velocity.y = -1f;
}
//player movement on both axis
float horizontal = Input.GetAxisRaw("Horizontal");
float vertical = Input.GetAxisRaw("Vertical");
Vector3 direction = new Vector3(horizontal, 0f, vertical).normalized;
velocity.y += gravity * Time.deltaTime;
controller.Move(velocity * Time.deltaTime);
if (Input.GetKeyDown("space") && isGrounded)
{
velocity.y += Mathf.Sqrt(jumpHeight * -2f * gravity);
}
if (direction.magnitude >= 0.1f)
{
//player turning depending on where moving
float targetAngle = Mathf.Atan2(direction.x, direction.z) * Mathf.Rad2Deg;
float angle = Mathf.SmoothDampAngle(transform.eulerAngles.y, targetAngle, ref turnSmoothVelocity, turnSmoothTime);
transform.rotation = Quaternion.Euler(0f, angle, 0f);
controller.Move(direction * speed * Time.deltaTime);
}
}
}