Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Hey i have a problem with my gun script.

Discussion in 'Scripting' started by ah123rock, Sep 29, 2016.

  1. ah123rock

    ah123rock

    Joined:
    May 18, 2016
    Posts:
    5
    My problem is that my ray just go up in the air instead of shooting foward from my character.
    using UnityEngine;
    using System.Collections;

    public class GunController : MonoBehaviour
    {
    public Transform spawn;


    public void Shoot()
    {
    Ray ray = new Ray(spawn.position, spawn.forward);
    RaycastHit hit;

    float shotDistance = 20;

    if (Physics.Raycast(ray, out hit, shotDistance))
    {
    shotDistance = hit.distance;
    }

    Debug.DrawRay(ray.origin, ray.direction * shotDistance, Color.red, 1);
    }
    }
     
  2. lordconstant

    lordconstant

    Joined:
    Jul 4, 2013
    Posts:
    389
    Rotate your spawn point so that the z axis is pointing the way you want to fire.
     
  3. ah123rock

    ah123rock

    Joined:
    May 18, 2016
    Posts:
    5
    Do this work on a top down shooter because its what im making :)
     
  4. lordconstant

    lordconstant

    Joined:
    Jul 4, 2013
    Posts:
    389
    Ah, so when you said up you meant north?

    If so then make sure that the spawn is a child of you character/weapon.
     
  5. ah123rock

    ah123rock

    Joined:
    May 18, 2016
    Posts:
    5
    I have puttet it in as a child and no not north litterally up in the air xD :D
     
  6. lordconstant

    lordconstant

    Joined:
    Jul 4, 2013
    Posts:
    389
    Then yes the rotation thing should fix it. Alternatively you could use .up instead, since your working in 2d the z axis comes out of the screen, thats why the ray is going up.