Raycasting 2D Java Script --- Always finds something even though I have no other colliders

I’m trying to make a script that shoots a raycast then runs a command if it detects a collider. However, I have no other colliders on screen other than the backgrounds, but those are set to ignore the raycast. What is going wrong? Here is my code: (it is in the update function)

var raycastDist = 1;
var hit: RaycastHit2D = Physics2D.Raycast(transform.position, -Vector2.right, raycastDist);

// If it hits something…
if (hit.collider != null) {
print(“Yes!”);

}
else { print(“Nope”);}

What is going wrong?

Maybe it’s detecting the collider that overlaps transform.position. You can turn on/off the ability to detect colliders that overlap the start-point of ray/line casts in the 2D physics settings with the property ‘RaycastStartsInCollider’

This feature was added in 4.5.5 patch 2.

just for a bit of extra info, you could also just under print(“Yes!”);, put in

Debug.Log ("Hit collider : " + hit.collider.tag);

or

Debug.Log ("Hit collider : " + hit.collider.name);

give you an idea what its hitting. if its got a tag, or just use the collider name depending on how your scene is set up.

Thank you! Turns out it was hitting its own collider. Just need to start the raycast in front of it. I appreciate it!

Just to ensure you got the correct info; if you’re hitting your own collider and the ray is starting inside that collider then turn-off the ‘RaycastStartsInCollider’ or for a less global solution, simply set the GO that contains this collider to a different layer than the things you’re trying to detect and specify the layers you want in the cast, assuming this is okay to do in your game.