[Not solved] Shooting a RayCast at mouse location

So, I’ve went through this series of tutorials:

The player shooting script:

using UnityEngine;
public class PlayerShooting : MonoBehaviour
{
    public static int damagePerShot = 20;
    public static float timeBetweenBullets = 1f;
    public static float range = 100f;
    float timer;
    Ray shootRay; //see what we hit
    RaycastHit shootHit; //return what we hit
    int shootableMask; //we can only hit shootable things
    ParticleSystem gunParticles; //ref
    LineRenderer gunLine; //ref
    AudioSource gunAudio; //ref
    Light gunLight; //ref
  
    float effectsDisplayTime = 0.2f; //how long are effects gonna be viewable
    void Awake ()
    {
        shootableMask = LayerMask.GetMask ("Shootable"); //shootable layer
        gunParticles = GetComponent<ParticleSystem> ();
        gunLine = GetComponent <LineRenderer> ();
        gunAudio = GetComponent<AudioSource> ();
        gunLight = GetComponent<Light> ();
    }
    void Update ()
    {
        timer += Time.deltaTime;
        if(Input.GetButton ("Fire1") && timer >= timeBetweenBullets && Time.timeScale != 0)
        {
            Shoot ();
        }
        if (timer >= timeBetweenBullets * effectsDisplayTime)
        {
            DisableEffects (); //turn back off
        }
    }
    //ref from another script
    public void DisableEffects ()
    {
        gunLine.enabled = false;
        gunLight.enabled = false;
    }
    void Shoot ()
    {
        timer = 0f; //reset timer; wait till next shot
        gunAudio.Play ();
        gunLight.enabled = true; //show light
        gunParticles.Stop (); //if they are still playing, stop them
        gunParticles.Play (); //start playing (sync all the components)
        gunLine.enabled = true; //enable the renderer
        gunLine.SetPosition (0, transform.position); //from 0 (begining of the barrel) to position
        shootRay.origin = transform.position; //start at the tip of the gun
        shootRay.direction = transform.forward; //z-axis (forward)
        //shoot at ray, if we hit something return the end of the line where its hit, if not, draw a long line
        if (Physics.Raycast (shootRay, out shootHit, range, shootableMask)) //shootray = that way; shoothit = what we hit; range = 100f; shootableMask = shoot things which are able to be shot
        {
            EnemyHealth enemyHealth = shootHit.collider.GetComponent <EnemyHealth> (); //if we hit something, get its script
            if(enemyHealth != null) //check if we hit nothing
            {
                enemyHealth.TakeDamage (damagePerShot, shootHit.point);
            }
            gunLine.SetPosition (1, shootHit.point); //line from begining to what we hit
        }
        else //if we dont hit
        {
            gunLine.SetPosition (1, shootRay.origin + shootRay.direction * range); //draw a line to end
        }
    }
  
}

Been making my own game for a month after that, added lots of stuff etc… The only thing I have left now that I’m not happy with is the shooting mechanism. Instead of the rifle straight line, I’ve added a laser with the same script and object as in the tutorial. It does locate the mouse location and shoots where it’s supposed to if my character is facing down, otherwise the laser is too much to the right/left.

My guess is that I need to reposition my Players child object “GunBarrelEnd” (from the tutorial), but I cannot seem to get it right no matter what I do. So, does anyone have any suggestions about positioning this game object? Or any other approach to this problem?

While I’m here, I would like to add a few spells also… should I follow the same shooting script in the tutorial and only add a different particle effect (given that I can somehow slowdown the RayCast - How?) or is there a different approach for spells?

Use something like:

playerCamera.ScreenPointToRay(Input.mousePosition);

1 Like

Sorry for the late response, I’m using an ortographical view, so what exactly would be playerCamera?

I’m having a hard time understanding exactly what kind of game this is from just a brief look at the tutorials (I’ve never done them). It looks like maybe it’s third person fixed-perspective, like a Contra game? As much information as you can give on how this game works and how the shooting is supposed to operate would be appreciated. There’s only so much I can infer from the code itself, especially if the shooting isn’t actually working properly right now.

It’s a basic survival game with enemies spawning at designated points and running towards you. The cameras projection is Ortographic, so yes, it’s kind of an third person side fixed perspective.

The Player has two ChildObjects, a Rifle (the machine gun you see) and a GunBarrelEnd (it isn’t visible, but it’s placed at the tip of the Rifle object) on which you add the shooting script so the bullets, “firing” light etc. come from the end of the rifle.

The script shoots a line (Ray) from the GunBarrelEnd location to the MousePointer location and draws thick a yellow line. It then returns (RayCastHit) the location of the object that the line collided with, if it’s an enemy, it gets it’s HealthScript and decreases the hp for a fixed amount.

The shooting works just fine, but the placement of the “drawn line” is wrong. I tried repositioning the GunBarrelEnd object, but no matter what I do, it will always shoot too much to the right or left (depending on my characters view - north or south).

This is generally explained, if you need any specific info I can go deeper into this. Thanks for your effort, much appreciated!

Whatever camera that you’re using to look through. player camera…main camera…whatever.

Sorry, I must’ve checked this thread just before leaving the house a few days ago and then forgot about it when I actually had time to reply. FYI, “orthographic” just means that the camera doesn’t have perspective distortion, and isn’t an indicator of the camera’s angle or placement.

As for the line being off, I’m uncertain as to whether the origin AND direction are off, just the origin, or just the direction from the origin. You mentioned that “rifle end” is a child of the character, along with the rifle, but is the “rifle end” a child of the rifle? Try pausing the game when turning around and firing and comparing the Transforms of the player, the rifle, and the rifle end. Use some Debug.Logs to print out values on each gun fire so that you can compare them to eachother and what you think they’re supposed to be, which should give you some hints as to what’s going wrong.

This is the kind of problem that’s really difficult to help somebody with, because it’s incredibly reliant on how the inspector values and associations are set up (what’s a child of what) along the kinds of data you can only get by debug logging and experimenting. All I can say is the code looks fine (unless I’m thick and overlooking something, which is also very possible).

The only thing I can think of is maybe simplify things by using the transform.forward of the player object for determining the fire direction, and not the transforms of the gun or gun-end objects (which might not be facing the direction you think they are anyways, if the gun wasn’t exported from the modeling program with an absolutely optimal origin and facing-direction). Also, problems with position and rotation that don’t occur when facing specific directions are often “compounding” problems. One transform is reliant on the settings of the parent transform, which is reliant on the settings of THAT parent transform, back to the root. If the main body is turning, and the child object is also turning at the same rate, then the child-of-a-child object will be turned twice as much.