Shoot arrow directly to mouse position

I have a 3D game with a crosshair that follows the mouse and a player on a tower that shoots arrows. The game is a top-down view. I want the arrow to move directly on the position of the crosshair and stay there once it hits something. But one problem I don’t know what to write to get the arrow to go the crosshairs position on click and keep going to the same position without updating to a new location once the crosshair moves. I tried using movetowards but it the arrow ends up moving with the crosshair.

You can use a RayCast to set a transform position, then moveTowards that position.

Whenever your mouse clicks on an object with a collider, this will return a Vector3 point, and you can moveTowards that.


It shows in the documentation I linked. What you’re looking for specifically is this:

    if (Input.GetMouseButtonDown(0)) {
                RaycastHit hit;
                Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);

This will shoot a raycast from the Main Camera (make sure it’s tagged as main) at the mouse position. So, we can set up an if statement to see if the Ray hits any colliders, and if it does, return the Vector3 point that it hits.

Vector3 endPoint = null;

if (Input.GetMouseButtonDown(0)) 
{
        RaycastHit hit;
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);

        if (Physics.Raycast(ray, out hit)
       {
            hitPoint = hit.point;
       }
}

Then you can MoveTowards the endPoint Vector3.

Sorry, I’m not very experienced with raycasts. How do you get the Vector3 point and use it in moveTowards