# Shoot bullet and control its speed

I’ve attached an image to help explain show what I’m doing. So far I have the ray being cast when the user “fires” and whatnot. I have it then instantiate a prefab in the direction of the cast ray. How do i get the prefab to move in the direction of the ray/shot but with the ability to control its speed? Below are the snippets of code I’m using to generate my bullets. Aside from this my other question is how do I make the bullet know whether it hits and object or not?

I’m excited to hear back and get this going. Thank you guys for all your help so far.

This javascript is on my camera.

``````var Bullet : Transform;
var projectile :  Rigidbody;

function Start () {
}

function Update () {
if(Input.GetButtonDown("Fire1"))
{
var shotDir = Input.mousePosition;
var ray : Ray = Camera.main.ScreenPointToRay (Input.mousePosition); // Construct a ray from the current mouse coordinates

var instantiatedProjectile = Instantiate(Bullet,transform.position,transform.rotation);

instantiatedProjectile.rotation = Quaternion.LookRotation(ray.direction);

Debug.DrawRay (ray.origin, ray.direction * 10, Color.yellow);
Debug.Log(shotDir);
}
}
``````

This javascript is on my prefab(bullet).

``````var speed = 300.0;

function Start () {

}

function Update () {
var dir = speed * Time.deltaTime;
transform.Translate(0, 0, dir);
}
``````

Simple example given in FPS Tutorial may answer your question. you can find the answers in the code snippet below.

``````function Fire () {
if (bulletsLeft == 0)
return;

// If there is more than one bullet between the last and this frame
// Reset the nextFireTime
if (Time.time - fireRate > nextFireTime)
nextFireTime = Time.time - Time.deltaTime;

// Keep firing until we used up the fire time
while( nextFireTime < Time.time && bulletsLeft != 0) {
FireOneShot();
nextFireTime += fireRate;
}
}

function FireOneShot () {
var direction = transform.TransformDirection(Vector3.forward);
var hit : RaycastHit;

// Did we hit anything?
if (Physics.Raycast (transform.position, direction, hit, range)) {
// Apply a force to the rigidbody we hit
if (hit.rigidbody)

// Place the particle system for spawing out of place where we hit the surface!
// And spawn a couple of particles
if (hitParticles) {
hitParticles.transform.position = hit.point;
hitParticles.transform.rotation = Quaternion.FromToRotation(Vector3.up, hit.normal);
hitParticles.Emit();
}

// Send a damage message to the hit object
}

bulletsLeft--;

// Register that we shot this frame,
// so that the LateUpdate function enabled the muzzleflash renderer for one frame
m_LastFrameShot = Time.frameCount;
enabled = true;