I’ve been trying to make my Player able to kill enemies using a Raycast (previously I used collision detection), however the code I tried using isn’t working. The enemies are not on IgnoreRaycast, and the code I am using is nearly identical to a string of previous, working code. Any ideas on how I might be messing up?
So, what’s wrong? Do you have errors in the console? Does it ever work?
When do you call this method?
It looks as though the ‘Destroy’ method has a common that is out of place.
You should check that hit isn’t null before using it.
You can include the distance in the raycast itself, as opposed to checking it afterwards.
You can use CompareTag which is better than ‘==’
You probably want to destroy the ‘hit.gameObject’ if successful, yes? Rather than the collider?
Those are some suggestions that come to mind, but without a bit more information, I’m not sure what to say.
Sorry for not making things clearer.
I do not get any errors, nor does the Debug display anything.
The method has not worked yet.
I call the method every frame.
I see, so you’re hitting yourself instead. Perhaps your ray is coming from the middle of the player?
Like if you do a debug draw ray or line from the position, can you see where it begins? Maybe you have to adjust it so it’s from the bottom?
Thank you so much!
I changed
“RaycastHit2D hit = Physics2D.Raycast(transform.position, Vector2.down);”
to
“RaycastHit2D hit = Physics2D.Raycast(transform.position + new Vector3(0f, -0.5f, 0f), Vector2.up);”
and it fixed my problem.
Also, I was wondering if there is a way to keep the raycast always down? When my player rotates, so does the raycast, and if it isn’t down then he dies instead of killing the enemy.
Thanks again for all the help. My problem was that I had it set to Vector2.up
(transform.position + new Vector3(0f, -0.3f, 0f), Vector2.up);
and replaced it with Vector3.up.
(transform.position + new Vector3(0f, -0.3f, 0f), Vector3.up);