Using a raycast to check for objects between two sprites?

Hi, all!

I’m using the 2D toolset from 4.3 to make a game where you grapple onto specific objects. I want to use a variable function to get a raycast/linecast from the player and the object to grapple onto it. I call this variable function OnMouseOver as a condition to check if there are objects in-between both sprites. I have tried using Physics2D but for some reason it is not recognizing the objects. The bool will always return false as if there is something in the way when there isn’t. I’ve tried both Physics2D and regular Physics Raycasts and Linecasts with no results. The player has a RigidBody2D and a CircleCollider2D while the node to attach to has a Circle Collider 2D.

Any ideas?

bool GrappleInRange(Transform origin, Transform end, float distance)
	{
		Ray ray = new Ray();
		ray.origin = origin.position;
		ray.direction = end.position - origin.position;
		bool hitGoal = false;
		RaycastHit2D col = Physics2D.GetRayIntersection(ray, distance);

		if(col)
		{
			print(col.collider.name);
		}

		if (col.transform != end)
		{
			hitGoal = false;
		}
		else if (col.transform == end)
		{
			hitGoal = true;
		}

		return hitGoal;
	}

void OnMouseOver()
	{
		if(GrappleInRange(player.transform, transform, connectionDistance) == true && connected == false)
		{
			connectIcon.SetActive(true);
		}
}

-Arnaldo

I would probably do it using Linecast, you also need to set some LayerMask’s, so it doesn’t get triggered by any type of collider, such as the player:

	private RaycastHit2D[] hits = new RaycastHit2D[2];
	private Vector2 grapplePos;
	private int openSpace;
	
	void GrappleCheck()
	{
		//grapple position stuff
		grapplePos = whatever;
		//check for objects between grapple position and this player
		openSpace = Physics2D.LinecastNonAlloc(transform.position, grapplePos,hits,(1 << LayerMask.NameToLayer("Ceiling")) | (1 << LayerMask.NameToLayer("Wall")) | (1 << LayerMask.NameToLayer("Ground")));
}

   void OnMouseOver(){
	
		//if only 1 collider in any of those Layer's was found, then you can grapple. If more than 1 or 0 were found, then don't grapple.
		if (openSpace == 1)
		{
			//do the grapple
		}
		
	}