Shooting at ground

For some reason I can’t shoot normally I just shoot at the ground. And I don’t know why.

Here’s my shooting script. I just attach it as a component to my character : Mainplayer


var ammo : int = 220;
var rocketPrefab: Transform; // your rocket prefab
var rocketSpeed: float = 20; // rocket speed
var spawnPoint: Transform; // empty object which defines the spawn point
var rateFire : float = 0.5;
var access : boolean = true;

private var canShoot : boolean;

function Start(){
canShoot = true;
function Update () {
if (ammo < 1){
canShoot = false;
function OnGUI(){
function ToFire(){
if (Input.GetButton("Fire1")){
   if (access){
      access = false;
      //here all the events to fire the gun //START NOW!
      if (canShoot){
  if (Input.GetButton("Fire1")){
  ammo -= 1;
    var ray: Ray = Camera.main.ViewportPointToRay(Vector3(0.5,0.5,0));
    var hit: RaycastHit;
    var dir: Vector3;
    if (Physics.Raycast(ray, hit)){
      dir = (hit.point - spawnPoint.position).normalized;}
      dir = ray.direction;}
    var rot = Quaternion.FromToRotation(rocketPrefab.forward, dir);
    var rocket = Instantiate(rocketPrefab, spawnPoint.position, rot);
    rocket.rigidbody.velocity = dir * rocketSpeed * 5;

  	//END NOW!
      yield WaitForSeconds(rateFire);
      access = true;
   function OnCollisionEnter(col : Collision){
   if(col.gameObject.tag == "AmmoPack"){
   ammo +=15;
   Destroy (GameObject.Find("AmmoPack"));

Thanks in advance!


I don’t get any errors either.

You calculate the rotation of your rocket in a pretty strange way. It is way better to make sure your spawnPoint points in the direction you want to shoot and then set your rocket accordingly:

var rocket = Instantiate(rocketPrefab, spawnPoint.position, spawnPoint.rotation);
rocket.rigidbody.velocity = spawnPoint.forward * rocketSpeed; // what is the 5 for??

Also you check for Input.GetButton(“Fire1”) twice which is redundant. You can remove the second statement to keep your code clean.
Furthermore your OnCollisionEnter is wrong too. You use GameObject.Find to destroy your ammopack. But GameObject.Find will return the first gameObject with name AmmoPack in your scene, which is not neccessarily the one you picked up. Use


instead. This will destroy exactly the ammoPack you picked up.