I’m attempting to get this player controller working right, and for the most part it does.
However, every so often the player will miss the hitbox and fall through the surface at speed. I’m not 100% sure why this is happening and I’m hoping someone can take a look at the code and offer a method of fixing it - so here we go:
using UnityEngine;
using System.Collections;
public class PlayerController : MonoBehaviour
{
public float PlayerSpeed;
public float JumpPower;
public float _Gravity = 9.89f;
public Vector3 Flip = Vector3.zero;
private Vector3 MoveDirection = Vector3.zero;
private bool FacingLeft = false;
private bool FacingRear = false;
public bool GroundContact = false;
private Rigidbody RigidBody;
private void Awake()
{
RigidBody = GetComponent<Rigidbody>();
}
private void Update()
{
DetectionRays();
MoveDirection.x = PlayerSpeed * Input.GetAxis("Horizontal");
if (GroundContact) {
MoveDirection.y = 0;
if (Input.GetButtonDown("Jump")) {
MoveDirection.y = JumpPower;
}
} else {
MoveDirection.y -= _Gravity * Time.deltaTime;
}
Vector3 movementVector = new Vector3(MoveDirection.x * Time.deltaTime, MoveDirection.y * Time.deltaTime, 0);
transform.Translate(movementVector);
}
private void DetectionRays()
{
DetectDown();
}
private void OnCollisionEnter(Collision Collide)
{
if (Collide.transform.tag == "Ground")
{
GroundContact = true;
}
}
private void DetectDown()
{
RaycastHit Obsticle;
Vector3 RayDownPosit = transform.position;
RayDownPosit.y += 0.8f;
Ray RayDown = new Ray(transform.position, Vector3.down);
Debug.DrawRay(RayDownPosit, Vector3.down, Color.red, 0.05f, false);
GroundContact = false;
if (Physics.Raycast(RayDown, out Obsticle, 0.05f))
{
if (Obsticle.transform.tag == "Ground")
{
GroundContact = true;
}
}
}
}