- Home /
RaycastHit2D to hit an enemy when player rotates. (Using keyboard input only)
Hi guys, new to Unity and C#. I'm trying to make my player shoot an enemy when facing him. I'm using RaycastHit2D to be able to hit the enemy:
RaycastHit2D hit = Physics2D.Raycast(transform.position, (transform.position).normalized, (transform.position).magnitude);
That doesn't work for a long distance. My player character needs to be very close to the enemy for the shot to be recorded.
But apparently, the second argument requires the position of the enemy or any point to which my player is facing when rotating. I have no idea how to do that. With mouse input, it works perfectly but I want to implement that using keyboard because that will allow me to add a second player. I've also tried using big float numbers for the third argument but nothing changed. Please help.
I have uploaded a picture below of the game I have so far. @Cherno @Bunny83 @Mike 3 @Eric5h5 @tanoshimi @duck @clunk47
If you look at the Scripting APIyou'll see that's not the way the Raycast2D parameters work. You need at least origin (transform.position) and the direction of the ray after that, and transform.position.normalized doesn't make any sense in that regard. It should be transform.right or transform.up, depending on how you sprite is rotated. Try out both, negative versions too, to find the correct forward direction of you character.
Answer by Priyanka-Rajwanshi · Apr 07, 2018 at 11:24 AM
The second argument is direction so try transform.up/transform.right. Maximize the distance as third argument.
Answer by poisoned_banana · Apr 07, 2018 at 01:32 PM
You need a direction as your second argument.
transform.up //green axis of the transform
transform.right //red axis of the transform
You could also calculate a vector pointing to an enemy with:
Vector3 direction = (enemy.position - player.position).normalized;
This for example will cast a ray from the transform's position, along the transform's green axis with a distance of 10:
RaycastHit2D hit = Physics2D.Raycast(transform.position, transform.up,10f);