How to set a object move forward extractly?

Hi lads, I’m new to Unity. I want to fire a missile when I push F key. I have a cube mesh called missileOut and the missile will fire from here.
This is the code of missileOut.js:

#pragma strict
var missile : GameObject;

function Start () {


function Update () {
		Instantiate(missile, transform.position, transform.rotation);

Here is the code of missile.js:

#pragma strict

function Start () {


function Update () {
	transform.Translate(0, 0, Time.deltaTime*10, Space.World);

When I press F key, the missile goes out. But its not go straight to the front. I have a corsshair in the middle and I place the missile to the middle then add to the prefab. How can I fix this problem?

You could have a raycast that goes from the crosshair forwards. When you aim, the raycast is hitting something, now you get the end point for your direction from the missile location.

So missile direction becomes:

(raycastHit.point - missile.position).normalized * speed

As a result your missile is going slightly upwards to wards what you aimed at.

If your raycast does not hit anything meaning you are aiming wrong or to the sky, you just throw the missile straight since it won’t hit anything anyway.

To make the missile go in a straight line. Use this code

// Our link to the projectile prefab
// MUST have a Rigidbody component attached
// For a grenade, set gravity on
// For a rocket, set gravity off
var projectile : Rigidbody;
// The amount of time between shots in seconds
var reloadTime = 1.0;
// This is the key we use to shoot
var shootKey = "f";
// Used to keep us from shooting too early
private var lastShot = -10.0

function Update () {
// This code checks if we hit the fire key and if we have reloaded
    if(Input.GetKeyDown(shootKey) && Time.time > lastShot + reloadTime) {

function Fire () {
// This creates the projectile and add force to it along the gun's z axis
    var instantiatedProjectile : Rigidbody = Instantiate (projectile, transform.position, transform.rotation);
    instantiatedProjectile.velocity = transform.TransformDirection(Vector3 (0, 0, initialSpeed));
// This keeps us from being hit with our own shot
    Physics.IgnoreCollision(instantiatedProjectile.collider, transform.root.collider);
// This starts the reload time
    lastShot = Time.time;

To implement this code. Create a JavaScript and paste in the code. Then attach the script to the object you wish to shoot from. Finally, define your projectile by dragging the prefab from the assets, into the slot for the projectile.

If you have any questions, just let me know. :slight_smile: