Physics2D.OverlapCircle doesnt work
Hello guys!
I have a problem with Physcis2D.OverlapCircle. In one tutorial i saw somebody use it as ground detector.
public bool grounded;
public float groundCheckRadius;
public LayerMask WhatIsGround;
public Transform groundCheck;
void FixedUpdate()
{
grounded = Physics2D.OverlapCircle(groundCheck.position, groundCheckRadius, WhatIsGround);
}
And it works nicely, so i thought i would use it to detect if player is standing on top of a platform. I tried to do it the same way but i cant get it to work properly. What i did is a created empty gameObject on each platform. Then i put a script on it where i wrote:
public bool onTop;
public LayerMask whatIsTop;
public float topCheckRadius;
public Transform topCheck;
void FixeUpdate()
{
onTop = Physics2D.OverlapCircle(topCheck.position, topCheckRadius, whatIsTop);
if (onTop)
{
Debug.Log("Works!");
}
}
Then in inspector i put the empty gameobject as the topCheck.position, i put some value for the topCheckRadius and lastly i create a layer called Top and then i select it in the WhatIsTop layermask.
But when i jump on the platform with player nothing happens.
Answer by Dream_in_code · Sep 04, 2016 at 10:55 AM
You dont need to make gameobjects on each platform instead add a gameobject as a child named "groundcheck" to your player.
public bool onTop;
public LayerMask whatIsTop;
public float topCheckRadius;
public Transform topCheck;/drag and drop "groundcheck" here else it wont work//
void FixeUpdate()
{
onTop = Physics2D.OverlapCircle(topCheck.position, topCheckRadius, whatIsTop);
} Adjust the "ground check" gamebject at the bottom of your player Inside "whatisTop" make sure Ground layer is selected.
What if we want to add multiple objects for groundcheck? How would the code go? Would we have to create multiple groundCheckRadius as well? Pertaining to his code above:
void FixedUpdate()
{
grounded = Physics2D.OverlapCircle(groundCheck.position, groundCheckRadius, WhatIsGround);
}
if you want to detect all objects inside the circle, you use
colliderList = Physics2D.OverlapCircleAll( same parameters );
Your answer
Follow this Question
Related Questions
See if objects overlap when user taps the screen 0 Answers
How to change animator states from a key press? 1 Answer
How do I Detect if an object has made a full rotation and gradually change its color 1 Answer
Error, Raycast2D call function in self script on duplicate object. 0 Answers
Find nearest enemy object in radius 2 Answers