Try to detect an object from another using Physics2D.Linecast

Hello !!

I am new to unity and maybe someone could help me.

I am building a 2D project and I don’t know what I am doing wrong.
I am trying to detect if a object has another object at its left side.
I have an object named Tile1, its a 2.5f square (prefab) with the Layer “Tile”, has a Box Collider 2D Component and the following script on it:

Vector2 lcc = new Vector2(transform.position.x - 2.5f ,transform.position.y);

Debug.DrawLine(transform.position,lcc,Color.white);

RaycastHit2D hit = Physics2D.Raycast(transform.position, lcc,2.5f);

if(hit.collider == null) {

print ("Nothing ON LEFT of " + name.ToString());

} else {

print (hit.transform.name.ToString() + " on the Left of " + name.ToString() );

}


RaycastHit2D leftColision = Physics2D.Linecast(transform.position,lcc,1 << LayerMask.NameToLayer("Tile"));

if(leftColision.collider == null) {

print ("Nothing ON LEFT of " + name.ToString());

} else {

print (leftColision.transform.name.ToString() + " on the Left of " + name.ToString() );

}

There is nothing on his left in the Scene.
I get the following result in the console:

Tile1 on the Left of Tile1

It seams to hit the same object.
In the Scene window the Debug.DrawLine seams to be correct but the result is not.

In the game I will have a lot of this object and what I need to detect when a “Tile” object has another “Tile” object a it left,right,up or down. In this way the object will know if can move to that directions or not.

Thanks and sorry for my bad English :wink:

Best Regards!!!

I was busy today, but managed to take a look this evening. Providing a project was helpful to getting a solution. The problem in that in 2D Raycasts from within an collider do not ignore the collider. I knew that, but in 3D colliders are one sided, so I read past the issue. Anyway here is one solution. I turn off the collider on the object doing the casting and then turn it back on. There may be some performance implications of having a bunch of objects turning their colliders on an off. If so, you’ll have to move the origin of your Raycast to just to the left of the tile.

using UnityEngine;
using System.Collections;

public class TouchController : MonoBehaviour {

	private Transform tileTrans;

	void Start() {
		tileTrans = transform;
	} 

	 void Update() {
		collider2D.enabled = false;
		RaycastHit2D hit = Physics2D.Raycast(tileTrans.position,Vector3.left, 4.0f, 1 << LayerMask.NameToLayer("Rail"));
		collider2D.enabled = true;
		Debug.DrawRay(tileTrans.position,Vector3.left * 4.0f,Color.magenta);

		if (hit.collider != null) {
			print(hit.collider.name + " is to the left of " + gameObject.name);
		}
	} 
}

Edit: I just though of another solution. If you have a reference to your ‘LookLeft’ game object you can do:

 RaycastHit2D hit = Physics2D.Raycast(lookLeft.position,Vector3.zero);

And for you have the layer mask is not needed, though you did get it right.