So I have made a script that moves my player character. There are a few things that I want to add, but I can’t figure them out by myself sadly. I have gone to around 16 different pages and have yet to find what I’m looking for. What I need help with is detecting when my player is standing on an object. I have a Boolean called IsGrounded and I need it to send false when I am in the air.
I thought I came up with a solid solution to the problem which would work. And it did! But… it’s very glitchy, almost to the point where it’s nonfunctional.
The script looks like this:
using UnityEngine;
using System.Collections;
public class PlayerColliderDetection : MonoBehaviour
{
public Player_Move ThePlayer;
void OnTriggerEnter(){
if (ThePlayer){ThePlayer.IsGrounded = true;}
}
void OnTriggerExit(){
if (ThePlayer){ThePlayer.IsGrounded = false;}
}
void OnTriggerStay(){
if (ThePlayer){ThePlayer.IsGrounded = true;}
}
}
Regarding my issue (I’m not very comfortable showing my scripts), my movement script does this:
public GameObject BlankObject; // A blank object to apply a collider to.
private GameObject GroundedCollider; // The object that will be set as the collider.
void Start()
{
// Creats a collider.
GroundedCollider = Instantiate(BlankObject, Player.transform);
GroundedCollider.AddComponent<SphereCollider>();
GroundedCollider.GetComponent<SphereCollider>().radius = 0.4f;
GroundedCollider.GetComponent<SphereCollider>().isTrigger = true;
GroundedCollider.AddComponent<PlayerColliderDetection>();
GroundedCollider.GetComponent<PlayerColliderDetection>().ThePlayer = Player.GetComponent<Player_Move>();
}
void Update()
{
RaycastHit hit;
if (Physics.Raycast(Player.transform.position, Vector3.down, out hit, 5000.0f))
{
HitY = hit.transform.position.y;
}
GroundedCollider.transform.position = new Vector3(GroundedCollider.transform.position.x, HitY, GroundedCollider.transform.position.z);
}
The idea is the collider follows the players x and z, uses a raycast pointing down from under the player, the position is retrieved, and the y is used. This would create a functional Vector3 every update for the collider, allowing it to follow. And the collider does follow the player. But, it bounces from the players feet, to the floor, or wherever they are standing on. It teleports on the y-axis… and it changes the IsGrounded Boolean constantly, even when I’m jumping. It’s frustrating and I would really appreciate some help!
Thankyou for anything,
Justin