- Home /
The question is answered, right answer was accepted
C# to find a Object in a direction on a 2D map
So I have a simple 2 layout, that i have a map generator placing a bunch of random blocks around, i set the generator to name each block based on its tile/array position, so Block at 1x1, Block at 1x9, etc. I have the player walking around ontop of the blocks, and want the player to be able to interact with blocks based on what direction there keys are, for example I hit Space, while moving to the Left, if there is a block to the left of me, runs a function attached in that blocks scripts, like if im holding a pick axe, and moving to the left while pressing space, it will try to mine that block. I thought using a 2d box colider as a trigger, but seems to make the player run the script on everything, so the ground there standing on, moving on, and if one is above also mines it. Is there a way to use like a raycast or something and say cast it from the player in the direction there moving, get that object, and have it work properly in a 2D game or is raycasting for 3D? or any other decent methods of finding only a single object in that direction closest to the player?
The reason I ask on the raycast (i have tried) it seems to always 'hit' the player, the code i tried with the raycast
if (Input.Get$$anonymous$$ey($$anonymous$$eyCode.Space))
{ // use tool based on direction moving
if(Input.Get$$anonymous$$ey($$anonymous$$eyCode.DownArrow))
{
RaycastHit2D hit = Physics2D.Raycast(player.transform.position, -Vector2.up);
if (hit.collider != null)
{
print ("Block hit: " + hit.collider);
}
}
}
Every Print it does says player no matter how close I am to any other block
:) nvm i fixed it, hope it works in the end not just as a temporary thing, but by going to edit-project settings - physics2d, and turning off the Raycast hit triggers, seems to skip the first one( player) and return the block right next to them :)