First person movement with character controller does not detect ground properly
I'm absolute beginner with Unity and I guess there were many questions similar to this but I couldn't find any with actual answers to my question.
i was following this tutorial on first person movement: https://youtu.be/_QajrabyTJc
I basically have exactly the same setup as in the video - except I have different player shape. After some very quick testing I've found out that it has some quirks I really don't like and I feel like there has to be a better way.
I've recorded a short gif showing my problems: https://i.imgur.com/sgs9v68.gifv
You can see 3 things:
An "air pillow" is slowing down the player right before they hit the ground
It is not letting player jump right next to a wall
Player can hang from a cliff and it wont register as being on ground therefore player is unable to jump and velocity is building up (you can see variables in the bottom right corner)
How to deal with it in a proper way? Maybe it is better to abandon character controller and change it to a rigid body?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
public CharacterController controller;
public float speed = 12f;
public float gravity = -19.62f; // -9.81 * 2
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);
}
}
Thanks
Your answer
Follow this Question
Related Questions
Moving a character with touch controls relative to target? 0 Answers
Problem with the Character Controller on the Y-Axis,Character Controller drifting in the Y Axis 0 Answers
Jump logic issues 0 Answers
CharacterController.Move with slow animals - they do not move 1 Answer
CharacterController.Move isn't setting collision flags 1 Answer