I’m working on jumping for my game (and I’m using a tutorial since my C# skills are not very great), and for whatever reason, when I try to make sure the player is not in the air using Physics.CheckBox, it always returns false. No matter what.
Player movement via WASD works fine, and the jumping works without checking if the player is grounded. But when I add this, it always returns false, and jumping becomes disabled.
Here is my code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CharacterMovement : MonoBehaviour
{
public float Speed;
public LayerMask groundLayers;
public float jumpForce;
public BoxCollider col;
private Rigidbody rb;
private bool isGrounded;
public Quaternion orientation = Quaternion.identity;
void Start()
{
rb = GetComponent<Rigidbody>();
col = this.gameObject.transform.Find("BoxCollision").GetComponent<BoxCollider>();
}
void Update()
{
PlayerMovement();
isGrounded = Physics.CheckBox(col.bounds.center, new Vector3(col.bounds.center.x, col.bounds.min.y, col.bounds.center.z), this.gameObject.transform.Find("BoxCollision").rotation, groundLayers);
if (isGrounded == false)
{
Debug.Log("False"); //always prints
}
if (isGrounded == true && Input.GetKeyDown(KeyCode.Space))
{
Debug.Log("hmm"); //never prints
rb.AddForce(Vector3.up * jumpForce, ForceMode.Impulse);
}
}
void PlayerMovement()
{
float hor = Input.GetAxis("Horizontal");
float ver = Input.GetAxis("Vertical");
Vector3 playerMovement = new Vector3(-ver, 0f, hor) * Speed * Time.deltaTime;
transform.Translate(playerMovement, Space.Self);
}
}
This isn’t a physics question but more of a scripting question. There’s just too much wrong here to cover it all.
Simply drag the BoxCollider2D onto the public “col” reference in the inspector and it’ll be done for you.
Take a look at the API reference for this to find out what it requires here. You’re passing in the center of the collider bounds as the first argument and then passing in the center of the bounds again with some odd thing for the Y. It requires the center and the half-size of the box. The BoxCollider size can be read here; It wants half of this.
You’re also doing that long-winded finding of that GameObject again. Find it once only, it’s not going to change then reference it. Doing this costs CPU time so you should avoid doing it as you move forward.
Not sure why you’re using a collider just to define an area as that’s an expensive way to do it. Maybe you’re using the collider for something else or maybe because you’re new this is all guesswork (I would suggest going through some tutorials if this is the case).
Well even after you fix the obvious incorrect usage of the above commands, I cannot debug it for you because only you know if it’s in the correct position in your scene etc but you’ve potentially made another mistake:
I would’ve thought the 2nd part would be “size.y”. Note you can simply do “col.size * 0.5f”