Including movement, gravity, jumping and collision detection.
I prefer not to use a character controller, I rather use rigidbody.
I know there’s similar questions and a lot of resources out there already, but I’m honestly unable to get my desired result no matter what I try.
However I will post my current code. It works pretty much like I want but it’s a bit glitchy.
Also I would be happy if you pointed out anything I should avoid in the future.
using UnityEngine;
using System.Collections;
public class Player : MonoBehaviour
{
private int moveSpeed = 8;
private int gravity = 10;
private float yVelocity;
private float vSpeed;
private float distToGround;
void Start()
{
distToGround = collider.bounds.extents.y;
}
void Update()
{
if(IsGrounded())
{
//vSpeed = 0;
yVelocity = 0;
if(Input.GetButtonDown("Jump"))
{
vSpeed = 5;
}
}
yVelocity -= gravity * Time.deltaTime;
vSpeed += yVelocity * Time.deltaTime;
rigidbody.velocity = new Vector3(Input.GetAxis("Horizontal") * moveSpeed, vSpeed, 0);
}
private bool IsGrounded()
{
return Physics.Raycast(transform.position, Vector3.down, distToGround);
}
}