- Home /
2D Ground Detection with OverlapCircle
Hello, I'm a newbie when it comes to Unity and Javascript. I'm making a game for a school project, a 2D platformer. However, I am encountering a problem with my ground check, it's always false! (Meaning that Unity thinks the player is still in the air, correct?). There must be something wrong, but I can't see it. Any help will be appreciated, thanks in advance!
This is my code:
var moveUp : KeyCode;
var moveDown : KeyCode;
var moveLeft : KeyCode;
var moveRight : KeyCode;
var isGrounded : boolean;
var groundCheck : Transform;
var groundRadius : float = 0.2;
var ground : LayerMask;
var jumpForce : int = 700;
var speed : float = 10;
function FixedUpdate ()
{
isGrounded = Physics2D.OverlapCircle(groundCheck.position, groundRadius, ground);
}
function Update ()
{
if (Input.GetKey(moveUp)) && isGrounded)
{
rigidbody2D.velocity.y = jumpForce;
}
else if (Input.GetKey(moveLeft))
{
rigidbody2D.velocity.x = speed * -1;
}
else if (Input.GetKey(moveRight))
{
rigidbody2D.velocity.x = speed;
}
}
You set a layermask in your check which is a little suspect for someone really new (i.e the last variable, ground). Did you mean to do that and did you configure the layermask in Inspector?
Answer by rubenedra · Mar 26, 2014 at 10:59 PM
Step 1:
You add the objects you want to a new or existing layer in the inspector (at the top right corner)
Step 2:
Then you define the layermask you want to check against :
Layermask myLayermask = 1 << LayerMask.NameToLayer ("myLayerName");
(Use this Layermask in your overlapCircle)
Btw, this example will ignore all layers exept the one with name 'myLayerName'.
Why suggest that bitshifting stuff which isn't simple for a new person to understand? If we expose a variable like
public Layer$$anonymous$$ask mylayer$$anonymous$$ask
in the editor we can just use the dropdown to check/uncheck if it's not going to need changing during play, there's no reason to get into that bitshifting.
Your answer
Follow this Question
Related Questions
Character motor ground detection problems 2 Answers
Player keeps switching between "grounded" and "not grounded" while running 0 Answers
How to have a placement marker on ground plane in AR Core ? 0 Answers
Checking if grounded using SphereCast -- Acting like Raycast 1 Answer
How to only Jump on Ground Items 1 Answer