# Shoot bullet along the ray cast

Hi,

I have some problem in shooting. how can I make my bullet move along ray? now I get the ray from launcher to hit point.Can I use this: transform.projectile.position=hit.point? I think it’s a little strange- -!

here is my code! Any idea is appreciate:P

``````var projectile :  Rigidbody;
var speed = 20;
function Update ()
{

if( Input.GetButtonDown("Fire1"))
{

var ray = Camera.main.ScreenPointToRay (Vector3(Screen.width/2,Screen.height/2));

var hit : RaycastHit;

if(Physics.Raycast(ray,hit))
{
Debug.DrawLine( transform.position, hit.point, Color.red);

Debug.Log(hit.point );

//  Instantiate (particle, transform.position, transform.rotation);

var instantiatedProjectile : Rigidbody = Instantiate(projectile, transform.position,   transform.rotation);

transform.projectile.position=hit.point;// is it right?
}

}

}
``````

You cannot do that no. I think you want to do something like:

``````if(Physics.Raycast(ray,hit))
{
Debug.DrawLine( transform.position, hit.point, Color.red);

Debug.Log(hit.point );
var instantiatedProjectile : Rigidbody = Instantiate(projectile, transform.position,   transform.rotation);

instantiatedProjectile.velocity = (hit.point - transform.position).normalized * muzzleVelocity;
instantiatedProjectile.rotation = Quaternion.LookRotation(instantiatedProjectile.velocity);

}
``````

I only changed 2 lines and that was the one you had a question about. Let me explain them. The first line finds the vector pointing at the hit point from the player, and it normalizes it. That way the bullet won’t travel faster if the shot is further away. Then we multiply by `muzzleVelocity` to set the bullets speed and direction. The second line is just for looks. It points the bullet at its rotation vector. That way it is facing the direction it is moving.

Here’s a C# version, working in Unity 4.5. This needs to be in the script on your active camera. Just add a prefab with a rigidbody in the Unity inspector (I used a sphere), and set the speed to whatever you want in the inspector. Note: I limited the raycast to 400.0f. If you limit it, be sure there’s something with a collider within that range or it won’t fire. But most games have buildings, walls, terrains, etc. so there’s almost always something for the ray to hit. It’s up to you.

``````public GameObject ball;
public float speed = 50;
RaycastHit hit;

void Start () {
hit = new RaycastHit();
}

void Update(){
if(Input.GetMouseButtonUp(0)){
Ray ray = this.camera.ScreenPointToRay(Input.mousePosition);
if(Physics.Raycast(ray, out hit, 400.0f))
{
GameObject newBall = Instantiate(ball, transform.position, transform.rotation) as GameObject;
newBall.rigidbody.velocity = (hit.point - transform.position).normalized * speed;
}
}
}
``````