I'm new to unity and want to make a small cube game where you can shoot at enemies (See picture below). Currently you can only shoot strait forward and you have to move to hit the enemies. I want to make the shooting more comfortable and shoot at the current mouse position. I only want to shoot in the x direction not up or down. But before implementing the shooting I want to make a LineRenderer which indicates were the player is shooting (as seen in the picture). Therefore my script doesnt include shooting a bullet for now.
Unfortunally I dont know how to convert the mouseOnScreen Position into world coordinates because I dont get how to get the correct depth for the player.
In my script the screenToWorld of the mouse is printing out nonesense because I didn t configure the depth rightful (I think).
Does somebody know how I can shoot at the current mouse position or clear me up on how to set the depth correctly so the screentoWorld is printing out correct/wanted values.
Here is the code I wrote:
public class ShootingAtScript : MonoBehaviour
{
private LineRenderer m_lineRenderer = null;
Vector3 linePointing;
private void Start()
{
linePointing = Vector3.zero;
m_lineRenderer = GetComponent<LineRenderer>();
}
void Update()
{
Vector3 mouse = Input.mousePosition;
mouse.z = transform.position.z; //With this I want to set the depth of the player
Vector3 mouseOnScreen = Camera.main.ScreenToWorldPoint(mouse); //Mouse on screen doesnt print out the values I want
linePointing = new Vector3(mouseOnScreen.x , transform.localPosition.y, 100); //Here I want to set the length of the linerenderer to 100 and make the y value stay were it is. I just want to move in the x direction.
m_lineRenderer.SetPosition(1, linePointing); //With this I set the second point of my linerenderer to make a straight line were the bullet would be flying
}
}
My Scene is looking like this: In this scene you can see the red cube which will be the player. The red line is the lineRenderer which should be indicating were the player is shooting. And this line I want to face to the current mouse position on the screen.
The solution I used was to cast a ray from the camera to the mouse and when the ray hit the ground I got the shooting direction I want.