Question by
diamondgaming250 · Jul 07, 2021 at 05:12 PM ·
collider2draycastingraycasthit2d
Raycast 2D detecting multiple objects in different positions
So, i'm working in a Plants Vs Zombies recreation, i have this script for spawning the plants, it is basically a Box Collider 2D within the size of the grass grid, i shoot a Raycast with the mouse position, the raycast is shooting constantly so that is has a hover effect, when you hover the mouse on the grid a transparent sprite of the plant is shown.
This is the script:
void PlantSpaceDetection()
{
RaycastHit2D hit = Physics2D.Raycast(Camera.main.ScreenToWorldPoint(Input.mousePosition), Vector2.zero);
if (hit.collider != null && hit.collider.gameObject.GetComponent<GridSpace>() != null
&& manager.plantToPlant != null && manager.previewPlantToPlant != null)
{
plantToPlantSprite.sprite = manager.previewPlantToPlant.plantPreviewSprite;
plantToPlantSprite.gameObject.transform.localPosition = manager.previewPlantToPlant.plantPreviewPosition;
if (Input.GetMouseButtonDown(0))
{
if (manager.CanSpawnPlant())
manager.SpawnPlant(new Vector2(plantSpawn.position.x, plantSpawn.position.y), this);
}
}
else
{
plantToPlantSprite.sprite = null;
plantToPlantSprite.gameObject.transform.position = ogPreviewPosition;
}
}
However if i have mutiple of this objects in the same scene the moment i hover the mouse the transparent version of the plant appears in everysingle grid, i did a Debug.Log and the hit.point appears to be the same for every grid, i'm not really sure why is this happening, any help is appreciated.
Comment