Unity 3D Raycasting Causing Trouble - Detecting Own Collider 50% of the time

Hey guys, I’m trying to develop a projectile-based bullet system in my game and one part of it is that it will fire a raycast, find the point of it, and then send a bullet on a Vector3.Lerp towards it. The issue is that a little over half the time the raycast will detect the player. The raycast is spawning inside of the collider and there are no other colliders on my game object. It only happens half the time, more often when moving and looking around, but happens while stationary too. Any movement done is done before the raycast is called. I’m lost right as I don’t know what else could be causing this glitch. Any insight would be very appreciated.

Here’s the bit of code that spawns the ray.

//Deals with the shooting mechanic
        if (Input.GetMouseButton(0) || Input.GetAxis("Fire") > 0) {

            //Add inaccuracy, spawn the bullet
            if (shooting == false) {

                //Create bullet spread
                accuracy = Vector3.forward;
                accuracy = cameraTransform.TransformDirection (accuracy);
                accuracy.x += Random.Range (-.04f, .04f);
                accuracy.y += Random.Range (-.04f, .04f);

                Physics.Raycast (cameraTransform.position, accuracy, out shootHit);
                newBullet = Instantiate (bulletPrefab, bulletSpawnPoint.position, bulletSpawnPoint.rotation);
                newBullet.GetComponent<Bullet> ().OnBulletSpawn (bulletSpawnPoint.position,shootHit.point,gameObject.transform,attack,playerInfo);

                //Adds a pause between shots
                shooting = true;
                StartCoroutine ("DelayFire");

            }

        }

There are a couple of ways you could fix this:

  • Have the origin of the raycast be slightly forward of the player
  • Use a LayerMask so that it only hits what you want.

The origin is spawned in the middle of the collider was its spawned from the camera transform, which is zeroed into the collider. Which is why this is confusing to me.

I’m not sure how I can use a LayerMask if this is a bullet system designed to fire at anything the player can point at

Put the player on a separate layer, then use a LayerMask so that it can hit everything else except the layer the player is on.