Well I am working on a jump script where a ball is only allowed to jump when it’s standing on something. I would like to constantly check if it’s colliding with the ground. Any help would be great. Here is my current script:
using UnityEngine;
using System.Collections;
public class ballConfig : MonoBehaviour {
public float speed;
public float jSpeed;
void Awake() {
speed = 0.9f;
jSpeed = 0.02f;
}
void Jump() {
for (int i = 0; i <= 20; i++) {
transform.Translate(new Vector3(0,jSpeed,0));
}
}
As Duugu mentioned above, raycasting down and making sure the distance is small enough is necessary.
If all you do is check for collisions you can actually keep jumping while touching the bottom or the sides of the object.
You can either use raycasting or colliding with a raycast, benefit to this would be that it does not keep raycasting all the time, but only does it when you collide with something.
OnCollisionEnter(Collision coll){
if(coll.tag == "Ground"){ //not necessary
if(Physics.Raycast(transform.position, Vector3.down, 5){ //5 = lenght of ray you may have to make it smaller
//Add your code (like setting a bool to true and then check that bool when you want to jump)
}
}
}
Don’t use inputs inside OnCollisionEnter because you’d have to press Space exactly when it collides, using OnCollisionStay could work tho. However I recommend using a bool, as instructed above.
bool canJump = false;
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.collider.tag == "ground");
{
canJump = true;
}
}
private void OnCollisionExit2D(Collision2D collision)
{
if(canJump == true) // this triggers only if the ball is not touching the ground anymore
{
canJump = false;
}
}
And then, use the canJump variable to tell if the ball can jump or not:
public float jumpForce = 8;
if (Input.GetAxisRaw("Vertical") > 0 && canJump == true) //if you want the ball to bounce repeatedly forever, make the first state ment ALWAYS TRUE for example: if (1+1=2 && canJump = true) {do something}
{
rb.AddForce(Vector3.up * jumpForce, ForceMode.Impulse);
} //the jump triggers if the up arrow or the W key is pressed
Note: On line 4 of the first script, it doesn’t necessarily have to be checking tags. You can also check the objects name using – collision.collider.name – if you want to!