I am currently working on a 3D platformer game where I want to add a jump mechanic to it. I wrote the code like this
using UnityEngine;
public class Jumping : MonoBehaviour
{
public float jumpForce = 5f;
public LayerMask Ground;
private Rigidbody cubeRigidbody;
void Start()
{
cubeRigidbody = GetComponent<Rigidbody>();
}
void Update()
{
isGrounded = Physics.Raycast(transform.position, Vector3.down, 0.1f, Ground);
// Check for player input to trigger a jump using the spacebar
if (isGrounded && Input.GetKey(KeyCode.Space))
{
cubeRigidbody.AddForce(Vector3.up * jumpForce, ForceMode.Impulse);
}
}
private bool isGrounded;
private void OnDrawGizmosSelected()
{
Gizmos.color = Color.red;
Gizmos.DrawRay(transform.position, Vector3.down * 0.1f);
}
}
I placed that C# scripting language code onto the player and the ground platform objects. But when I clicked play, nothing happened. Space, up arrow and nothing. I tried using the same code for another project and it still doesn’t work. Is there an error in my code? Or did I just not implement it properly in my Unity project?
My player object has a box collider, 3D rigidbody and my ground object has a box collider.
My unity version is 2020.3.0f1
You are probably casting a ray that is too short. if your collider is larger than 0.1f then the ray will not hit anything. You could make the ray longer or add a offset to the origin to make it start from the bottom of your collider.
– oskarasd123