Cant get a Prefab to fire where camera is looking!

Hi, im trying to get an object to spawn from the main camera which fires in the direction the camera is looking when i press space. Im working on trying to create a shooting effect so wherever the camera looks u can shoot the 'ball' but i cant get it to work! cheers!

var spawnPos : Transform;

var ball : Rigidbody;

function Update () {

if(Input.GetButtonUp("Jump")){ rigidbody.velocity = transform.forward * 10; }

var pFab : Rigidbody = Instantiate(ball, spawnPos.position, spawnPos.rotation);

var fwd : Vector3 = spawnPos.forward;

}

1 Answer

1

You can use this:

var projectile: Rigidbody;
var BulletSpeed = 10;

function Update () {
    // space was pressed, launch a projectile
    if (Input.GetButtonDown("Jump")) {
        // Instantiate the projectile at the position and rotation of this transform
        var clone : Rigidbody;
        clone = Instantiate(projectile, transform.position, transform.rotation);

        // Give the cloned object an initial velocity along the current 
        // object's Z axis
        clone.velocity = transform.TransformDirection (Vector3.forward * BulletSpeed);
    }
}

Now all you have to do is give a empty GameObject this .js and the same directions as your camera/ship, to make it fire straight forward.