I’m messing around with unity and currently trying to get a ball rolling around and jumping on a platform. currently, i’ve found a “character controller” script from unity that allows me to control the movement of the ball. however, the “controller.isGrounded” thing it uses seems very arbitrary; i’ve added debug log in the script to log the state of “controller.isGrounded” and no matter what i do, it seems to be “False” most of the time, only seemingly randomly switching to “True” sometimes. and the part of the script that controls jumping relies on the “controller.isGrounded” to determine whether the ball is “grounded” to allow it to jump.
So I decided to try and use collisions to detect whether the ball is “grounded” instead, swapping “groundedPlayer” with “collision.gameObject.name == ground.name”. however, this just gives me a “Object reference not set to instance of an object” error. i’m assuming this is bc my implementation of collision detection is wrong, but i’m not sure what the right way to do it is.
ball control script, for reference:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class NewBehaviourScript : MonoBehaviour
{
private CharacterController controller;
private Vector3 playerVelocity;
private bool groundedPlayer;
public float playerSpeed = 2.0f;
private float jumpHeight = 1.0f;
private float gravityValue = -9.81f;
public GameObject ground;
private Collision collision;
// Start is called before the first frame update
private void Start()
{
controller = gameObject.AddComponent<CharacterController>();
}
// Update is called once per frame
void Update()
{
groundedPlayer = controller.isGrounded;
if (groundedPlayer && playerVelocity.y < 0)
{
playerVelocity.y = 0f;
}
Vector3 move = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
controller.Move(move * Time.deltaTime * playerSpeed);
if (move != Vector3.zero)
{
gameObject.transform.forward = move;
}
//Debug.Log(collision.gameObject.name);
if (Input.GetButtonDown("Jump") && collision.gameObject.name == ground.name)
{
playerVelocity.y += Mathf.Sqrt(jumpHeight * -3.0f * gravityValue);
}
playerVelocity.y += gravityValue * Time.deltaTime;
controller.Move(playerVelocity * Time.deltaTime);
}
}