Accurately shooting a raycast

I know how to fire a raycast from a spawn point forwards, but am currently unable to shoot rays to the centre of the screen, where my crosshair is.

var effectInstance = Instantiate(ShotSpell1, spawnPoint.transform.position, new Quaternion()) as GameObject;
            var effectSettings = effectInstance.GetComponent<EffectSettings>();
            effectSettings.UseMoveVector = true;
            effectSettings.MoveVector = Camera.main.transform.forward;

I am sure that it is down to the final line, but am not entirely sure what to put in the final line of code. Should I consider the rotation of Camera.main or spawnPoint?

Is there some way of specifically ordering that all rays shoot the very centre of the screen?

Thanks in advance.

So you want to click and then something somewhere should spawn something that moves to the current center of the screen (but with the correct distance from the camera)?
from your code and your question I guess your game is in 3D.

what you need to do is casting a ray from the camera position into the direction of the camera.
then you need to do a Raycast check against the geometry (probably the terrain) to retrieve the point where the ray intersects the geometry (you may move a few distance backwards to the camera if the target should be a little bit above the surface).

with that point you can determain the direction to shoot at by subtracting the spawn position from the calculated intersection position. Normalize it afterwards to get an direction vector.

BTW: if your terrain is flat and axis aligned you don’t have to make a physics raycast. Instead you can evaluate the distance with a simple formular.

Hope this helps. If not: describe a little more what you are trying to achieve and tell which steps are unclear.

1 Like

You can shoot from the center of the screen outward into the “world space” using several different methods, but the easiest is Camera.ViewportPointToRay. It has the added benefit of not only giving you the coordinates, but actually just creating the whole ray for you. Just feed it a (.5f, .5f) Vector2 value (which, in viewport coordinates means “halfway vertical up the screen and halfway horizontal across the screen”) and it’ll give you back a ray. Fire a raycast using that ray with whatever distance you feel is appropriate, and you’re gold.

1 Like