- Home /
Physics2D Raycast, check if my raycasthit2D.collider is the same as my gameObject
I have two colliders, a box2d collider and a circle2d collider on my game object.
I'm trying to send out a Physics2D raycast:
collider2D.enabled = false;
RaycastHit2D hit;
Debug.DrawRay (transform.position, direction*directionDistance, Color.green);
hit = Physics2D.Raycast (transform.position, direction, directionDistance);
collider2D.enabled = true;
When I Debug with the following:
Debug.Log ("collider that's hit");
Debug.Log (hit.collider);
Debug.Log ("this game object");
Debug.Log (this.gameObject.collider2D);
My hit.collider is
UnityEngine.CircleCollider2D
My this.gameObject.collider2D is:
UnityEngine.BoxCollider2D
How do I do a check for my circleCollider?
I just want to make sure the raycast2D.collider is not checking for itself, so I can go ahead and move my object.
I also tried explictly casting for a circle:
Debug.Log ("hit------");
Debug.Log (hit.collider);
Debug.Log (this.gameObject.collider2D as CircleCollider2D);
Debug.Log ("endhit------");
However for this.gameObject.collider2D as CircleCollider2D I then get null.
Answer by Itaros · Oct 23, 2014 at 06:25 AM
Kinda like that:
Collider2D[] coll = this.GetComponents<Collider2D>();
bool isMe=false;
foreach(Collider2D c in coll){
if(hit && hit.collider==c){isMe=true;break;}
}
This worked great, thanks!
As a note I ended up having to use RaycastAll ins$$anonymous$$d of just Raycast...Raycast always only returns one, and that seemed to be (invariably?) the object (collider) it originated from, if I set the origin to be the transform.position of my gameObject.
I tried moving the origin of the Raycast to be outside, but was hard to put in in a place that wasn't going to skew the angle I wanted.
bool hasObstacle = false;
RaycastHit2D[] hits;
hits = Physics2D.RaycastAll (transform.position, direction, directionDistance);
foreach(RaycastHit2D hit in hits) {
if (hit && hit.normal != -direction) {
hasObstacle = true;
}
}
Your answer
Follow this Question
Related Questions
Why does Physics2D.Capsule/Circle/BoxCast's hit point and distance not line up? 0 Answers
Detecting if the object is hit by LineRenderer 1 Answer
Raycast ignore itself 5 Answers
Raycast2D Layermasks and incomplete docs 1 Answer
Questions about movement on uneven/slopped terrain and terrain coliders 0 Answers