Ziad
1
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
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.
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!