Hi,
I am trying to retrieve an array of objects in a small area around where the mouse is clicked. This is what I have (not working):
void Update () {
if (Input.GetButtonDown ("Fire1"))
PlaceTurret (Input.mousePosition);
}
public void PlaceTurret(Vector2 mousePosition)
{
Collider2D[] hitColliders;
RaycastHit hit = RayFromCamera(mousePosition, 1000.0f);
Vector2 center = new Vector2(hit.point.x, hit.point.y);
hitColliders = Physics2D.OverlapCircleAll(center, 1f, 1 << 9);
if (hitColliders.Length == 0) {
Debug.Log ("CAN PLACE");
//Instantiate (spawnable, position, transform.rotation);
} else {
Debug.Log(hitColliders[0].name);
Debug.Log ("CANT PLACE");
}
}
public RaycastHit RayFromCamera(Vector3 mousePosition, float rayLength)
{
RaycastHit hit;
Ray ray = Camera.main.ScreenPointToRay(mousePosition);
Physics.Raycast(ray, out hit, rayLength);
return hit;
}
I am doing this to see if a gameobject can be placed at the location clicked. The issue is that it always returns that it can be clicked or, if I expand the collider radius past a certain point, it will always return the same object being in range of the click. Is my ray cast not correct? . The object I am trying to find if it is touching is on layer 9.
Edit: So I just realized the raycasting I was doing is using the 3D variants of them while I am in 2D. I tried to change these over but screenpointtoray is only in 3D. Is there a substitution or better approach for this?