Why does my 2D raycast not always work?

Hi everyone,

For a school project I am making this game. I usually make 3D games, but this is my first serious hit on making 2D games. Everything works out for now, except one thing.

I have a problem with getting the mouse position through correctly.

I have a playfield located in all axis on zero, with a span of roughly 25 in every direction.
The mouse position that I am receiving however, is varying from 0 on all axis till 500+.

I think this is the main problem, but the weird thing is that my build system (which uses the same raycast) does work and destroy (using the same raycast again) works only sometimes. This can be seen in the GIF.

Bug in the game

This is the code of the raycast im requesting:

Physics2D.Raycast(Camera.main.ScreenToWorldPoint(Input.mousePosition), Vector2.zero

Does anyone know how to solve this?

Thanks upfront,

Jenoah

Where is the camera in relation with the play area on the z axis?? The ScreenToWorldPoint is returning you the camera position in world coordinates on the axis it is facing with the way you have it in your code. If your play area is 10 units away from the camera, you would pass 10 as that second parameter as it corresponds to how many units away from the camera the position returned should be. The mouse position you are receiving is in pixels by the way, so 0 - 500 is ok, that is why you are translating that into world coordinates where your 500 pixels can represent any amount of units depending on multiple factors