- Home /
How to set circle collision detectors more accurate
Hi,
I have a rectangle object, the player. I have a collection of cloned circle shaped objects.
When the player collides with a circle the game ends, see code below. The problem is that at certain angles the collision is inaccurate. The rectangle never touches the circle yet a collision is detected. If anyone could point me how to make it more accurate it would be much appreciated.
void OnCollisionEnter2D(Collision2D col)
{
if (col.collider.name == "Point(Clone)") {
Die ();
}
}
For my circles I am doing a transform.position to change the starting position to random and a transform.localscale to change the size randomly
Answer by Invertex · May 08, 2014 at 08:34 PM
They should be pretty accurate... But if it's causing you issue, you could use OverlapCircle instead of a Collider, which will be fully consistent, only when something actually enters the circle.
http://docs.unity3d.com/Documentation/ScriptReference/Physics2D.OverlapCircle.html
Thanks, Any idea how I would edit my code above to use overlap circle ins$$anonymous$$d.
Bear in $$anonymous$$d all circles are different sizes.
Thanks again
It depends... OverlapArea would be more efficient, by only calling it on your player sprites, ins$$anonymous$$d of OverlapCircle on all your other sprites. Here's the simplest implementation for you:
private Vector2 sBounds;
private Collider2D hitCol;
private Vector2 curPos;
void Start ()
{
sBounds = GetComponent<SpriteRenderer>().bounds.extents;
}
void Update ()
{
curPos = transform.position;
if( (hitCol = Physics2D.OverlapArea(curPos - sBounds,curPos + sBounds))
&& hitCol.name == "Point(Clone)")
{
Die();
}
}
Hi Invertex,
Thanks for the code above.
I have tried it, however it seems to be worse with this method than previously. Sometimes doesnt detect collision when there is one. I'm not sure if its something to do with my circular Textures. Its just a png I created with a transparent background. Its like as if the collision is detected on an invisible square around the circle and not the circle itself.
try changing collision detection, in collider settings. are you overriding any positions using transform position etc?
For my circles I am doing a transform.position to change the starting position to random and a transform.localscale to change the size randomly
Your answer
Follow this Question
Related Questions
How to check Hypothetical Collisions in 2D 1 Answer
How to get an AI move around in an asteroid field 0 Answers
General Unity 2D Character/Environment Control Questions 2 Answers
No changing Linear Drag (.linearDrag) on rigidbody / rigidbody2D in code? 1 Answer
Cloud recognition in Vuforia 0 Answers