3

Collider.Raycast -> Casts a Ray that ignores all Colliders except this one.

Collider2D.Raycast -> Casts a ray into the scene starting at the collider position ignoring the collider itself.

I want to use it like Collider.Raycast where it "ignore all except this", but i'm using Collider2D now, i need to cast a raycast and check if it hit with only that specify Collider2D, or is there any better way?

FunFair
  • 191
  • 1
  • 12

1 Answers1

-3

For Raycasts in 2D, you should ideally be using the Physics2D.Raycast method

(from the Unity Documentation)

RaycastHit2D hit = Physics2D.Raycast(transform.position, -Vector2.up);

if (hit.collider != null) {
    float distance = Mathf.Abs(hit.point.y - transform.position.y);
    float heightError = floatHeight - distance;
    float force = liftForce * heightError - rb2D.velocity.y * damping;
    rb2D.AddForce(Vector3.up * force);
}

This should provide you with all of the documentation you need. The Physics2D class also has a number of useful related functions such as circle casts, line casts and also information on how to ignore certain layers in raycasts.

To save you time, here is the full Physics2D.Raycast method, including optional variables.

public static RaycastHit2D Raycast(Vector2 origin, Vector2 direction, float distance = Mathf.Infinity, int layerMask = DefaultRaycastLayers, float minDepth = -Mathf.Infinity, float maxDepth = Mathf.Infinity);

Good luck with your project!

  • 2
    Thanks for the quick reply! however this doesn't provide the function to raycast only a specify collider like Collider.Raycast do, which is what i need in my case. – FunFair Apr 23 '18 at 07:40