Shooting with camera on rails

Hi all, im quite new to Unity and am working on a simple shooter on rails, however I am having trouble getting the projectiles when you shott to head out in the right direction.

I have made a gun object that is attatched to the camera, I need the gun object to shoot out wherever the player clicks, im not sure if this is the best way to do it or if I should maybe use raycasting instead?.

Here is the code I have so far, any help would be greatly appreciated.

#pragma strict
var projectile : Rigidbody;
var speed = 20;
var mousex = 0;
var mousey = 0;
var gun : GameObject;

function Start () {

}

function Update () {
  mousex = Input.mousePosition.x/2;
  mousey = Input.mousePosition.y/2;
  gun.transform.LookAt(Vector3(mousex,mousey,0));
  
  if (Input.GetButtonDown("Fire1"))
  {
    var instantiatedProjectile : Rigidbody = Instantiate( projectile, transform.position, transform.rotation);
    instantiatedProjectile.velocity = transform.TransformDirection( Vector3(0,0, speed));
    Physics.IgnoreCollision( instantiatedProjectile. collider,transform.root.collider);
  }
}

How fast is your projectile ? Bullet, arrow, bubble ? If the projectile is too fast to even be seen, don’t bother with a GameObject at all, use a raycast and something for the impact. For an arrow-like speed, it becomes relevant to have a body.

Hi, its a Rocket, so I do want it to be visible, ive no idea how to raycast either.

Thanks for the reply.

Your first problem is in the fact that you are just using the mouse coordinates - they aren’t in work space so that will give you a problem right there :slight_smile:

You want to use:

 var ray : Ray = Camera.mainCamera.ScreenPointToRay(Input.mousePosition);

This gives you a ray, now you need to decide how far from the camera the target is and do this

 gun.transform.LookAt(ray.GetPoint(distanceFromTheCamera))

Hi Mike, That works great, thank you.