Search Unity

How to shoot at crosshair?

Discussion in '2D' started by JMaracle, Apr 23, 2019.

  1. JMaracle

    JMaracle

    Joined:
    Apr 21, 2019
    Posts:
    2
    Hello lads, I'm just getting into game development and have managed to make my character run around the game scene but now Im faced with trying to make him shoot at at a crosshair I have dragged into the scene as well. I'm stuck at a point where I can't figure out how to make the crosshair follow my mouse, and then shoot the projectile at the crosshair... all help is appreciated, thank yall
     
  2. halley

    halley

    Joined:
    Aug 26, 2013
    Posts:
    2,445
    Usually a crosshair reticule is drawn on the screen in 2D as a part of a Canvas. Then whenever your crosshair gets an Update() call, you reposition the crosshair based on the current Input mouse coordinates. There is still a difference between the coordinates the mouse uses and the coordinates in your viewport. https://docs.unity3d.com/ScriptReference/Camera.ScreenToViewportPoint.html

    But it's okay to have a crosshair or whatever target you want as a part of the game world too.

    To figure out where in the game world corresponds to the mouse coordinates, you need to convert the coordinates. This is done in 3D worlds with the Camera's ConvertScreenToWorld function, followed by a Physics.Raycast to figure out what position in the world behind the mouse is not just empty air. https://docs.unity3d.com/Manual/CameraRays.html
     
    Lorrak likes this.