Hi, I have a simple ground game object and a cuboid for a player.
I’m trying to make the player stand on the ground without falling through or bouncing, so I have a while loop to make it stand on top of the ground, but it always crashes! I even made a separate script to detect collisions to resolve the while loop.
Here are my scripts:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerHitboxScript : MonoBehaviour
{
float yV = 0;
public float gravity;
int inAir = 0;
public float jumpHeight;
public float runSpeed;
public PlayerCollisionDetection detection;
// Start is called before the first frame update
void Start()
{
transform.position = new Vector3(0.5F, 5.5F, 1.5F);
}
// Update is called once per frame
void Update()
{
yV -= gravity;
transform.Translate(0, yV, 0);
inAir += 1;
if (Input.GetKey(KeyCode.Space))
{
if (inAir < 8)
{
yV = jumpHeight;
transform.Translate(0, 0.001F, 0);
}
}
if (Input.GetKey(KeyCode.LeftArrow))
{
moveSteps(-runSpeed, "z");
}
if (Input.GetKey(KeyCode.RightArrow))
{
moveSteps(runSpeed, "z");
}
if (Input.GetKey(KeyCode.UpArrow))
{
moveSteps(-runSpeed, "x");
}
if (Input.GetKey(KeyCode.DownArrow))
{
moveSteps(runSpeed, "x");
}
if (yV > 0)
{
standOnGround(true);
}
else
{
standOnGround(false);
}
}
void standOnGround(bool movingUp)
{
while (detection.touchingGround)
{
if (movingUp)
{
transform.Translate(0, -0.0001F, 0);
}
else
{
transform.Translate(0, 0.0001F, 0);
inAir = 0;
}
yV = 0;
}
}
void moveSteps(float steps, string direction)
{
if (direction == "x")
{
transform.Translate(steps, 0.001F, 0);
if (detection.touchingGround == true)
{
transform.Translate(-steps, 0, 0);
}
}
else
{
transform.Translate(0, 0.001F, steps);
if (detection.touchingGround == true)
{
transform.Translate(0, 0, -steps);
}
}
}
}
and
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerCollisionDetection : MonoBehaviour
{
[HideInInspector]
public bool touchingGround = false;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
}
void OnTriggerEnter(Collider otherObject)
{
if (otherObject.gameObject.tag == "Ground")
{
touchingGround = true;
}
}
void OnTriggerExit(Collider otherObject)
{
if (otherObject.gameObject.tag == "Ground")
{
touchingGround = false;
}
}
}