- Home /
making the weapon shoot whatever the crosshair is on
i'm making FPS Game and i want the projectile to go at the center of the screen........ no mater how far or how near is the object that i'm looking at
Answer by aldonaletto · Aug 13, 2011 at 12:34 AM
You can use ViewportPointToRay to create a ray from the screen center and get the hit point as your target, then get the direction from the vector (hit.point - spawnPoint.position):
EDITED: Altered to shoot even when nothing was hit by the raycast - it uses the ray direction in this case:
var rocketPrefab: Transform; // your rocket prefab var rocketSpeed: float = 20; // rocket speed var spawnPoint: Transform; // empty object which defines the spawn point
function Update () { if (Input.GetButtonDown("Fire1")){ // create a ray from the center of the screen var ray: Ray = Camera.main.ViewportPointToRay(Vector3(0.5,0.5,0)); var hit: RaycastHit; var dir: Vector3; if (Physics.Raycast(ray, hit)){ // if something aimed // find the direction from spawnPoint to the target dir = (hit.point - spawnPoint.position).normalized; } else { // if there's nothing, use the ray direction dir = ray.direction; // spawnPoint.forward works too (see note below) } // ensure the rocket will born pointing to the target var rot = Quaternion.FromToRotation(rocketPrefab.forward, dir); // instantiate the rocket var rocket = Instantiate(rocketPrefab, spawnPoint.position, rot); // launch the rocket rocket.rigidbody.velocity = dir rocketSpeed; } } NOTE:* An alternative could be to use the spawnPoint.forward direction instead of ray.direction. This makes little difference unless the spawPoint is much lower than the camera.
O$$anonymous$$G Thats cool thnx alot......... but there is something about it ... i want to shoot even if i'm not looking at anything cuz this script making me shoot only if i'm looking at something
Yes, this script only shoots if there is something aimed because it needs the hit.point. But you can use ray.direction in other cases. I edited my answer to include this case.
Answer by Bosstvgames · Mar 17, 2014 at 01:46 AM
The script works GREAT! but I have one question I`m making a fps game so I would like to have the gun shoot straight at the cursor or at the cross hair its set at the middle of the screen so please help me if can!