- Home /
Check if circle player is on the ground
hi
How can I check if a circle is on the ground like picture below ?!
i have roof and wall in my game , so if i check ground collision for all around of circle , it can jump sevral times on walls or roof.
sorry for my bad english.
Answer by VivienS · Jan 28, 2016 at 08:06 PM
Hey there,
If you're using simple colliders and
void OnCollision2D (Collision2D collision) {...}
or its 3D counterpart, check out the Collision2D.contacts. It's an array that contains the exact positions of the collision points in world space. You can transform them easily into local space or just compare them with the world position of your collider (below => probably hit floor, same => probably hit wall, ...).
If you're using a CharacterController, you can check its CollisionFlags to see where the last hit took place.
Cheers.
Answer by coolraiman · Jan 28, 2016 at 07:46 PM
Use box collider (boxCollider2D if your game is in 2D) and give them the name "ground" and align their position and size with your ground surfaces
add a rigibody on your circle and add a script on your circle with something like this exemple
public class ExampleClass : MonoBehaviour {
void OnTriggerEnter(Collider other) {
if(collider.name == "ground")
{
//do your stuff here
}
}
}
Answer by wolfenstien98 · Jan 29, 2016 at 06:36 AM
If you are using a Character Controller you can use the built in method isGrounded.
Otherwise I would suggest using a RayCast
Answer by Fogwalker · Jan 31, 2016 at 02:38 PM
I think I know you problem... using charactercontroller might not work in your situation although it might.
If you are doing this 2d.. watch this video.
https://www.youtube.com/watch?v=2akPDnmSfu8
If you are doing this in 3d watch the video, but the code will be close to this.
using UnityEngine; using System;
public class jump : MonoBehaviour { // These are the variables for detecting ground
public Transform groundCheck;
public float groundCheckRadius;
public LayerMask whatIsGround;
private bool grounded;
// This is for the jump variables
public float thrust;
public Rigidbody rb;
// Use this for initialization
void Start()
{
rb = GetComponent<Rigidbody>();
}
// Update is called once per frame
void Update()
{
grounded = (Physics.CheckSphere(groundCheck.position, groundCheckRadius, whatIsGround));
if (Input.GetKeyDown("space") && grounded)
{
rb.AddForce(Vector3.up * thrust);
}
}
}