Jack Godfrey
Jack Godfrey

Reputation: 23

Unity3D - Raycast not hitting correct position

I'm trying to make a gun by shooting a ray from the centre of the camera which the gun is a child of, I also have a particle effect where the impact happens only, the impact happens in the wrong position.

I did Debug.DrawLine and saw that the origin of the ray was happening 0.8 units above the center of the camera, and it sometimes hits directly on the camera Here is the gun script

using UnityEngine;

public class GunShoot : MonoBehaviour
{
    public float gunDamage = 1f;
    public float fireRate = .1f; // wait x seconds to fire again
    public float weaponRange = 100f;
    public float hitForce = 100f;


    public Camera playerCam;
    //public ParticleSystem muzzleFlash;
    public GameObject impactEffect;

    private float nextFire; // Holds the time for which the gun is able to fire again

    void Update()
    {
        Shoot();
    }
    public void Shoot()
    {
        if (Input.GetButtonDown("Fire1") && Time.time > nextFire)
        {
            nextFire = Time.time + fireRate;
            RaycastHit hit;

            if (Physics.Raycast(playerCam.transform.position, playerCam.transform.forward, out hit, weaponRange)) // Center of the camera, directly forward, hat it hits and that infomation, the range of the weapon 
            {

                Target target = hit.transform.GetComponent<Target>();

                if (target != null)
                {
                    target.TakeDamage(gunDamage);
                }

                GameObject impactGameObject = Instantiate(impactEffect, hit.point, Quaternion.LookRotation(hit.normal));
                Destroy(impactGameObject, .15f);
            }
        }
    }   
}

I have been using a tutorial by Brackleys https://www.youtube.com/watch?v=THnivyG0Mvo but i followed it perfcetly (execpt chaning some variable names) and i cannot see where it is going wrong.

I cant just reduce the high of the initial ray as it sometimes maybe 1/10 times shoots from the right position

As you can see it clearly isn't shooting from the middle where the crosshair is enter image description here

Any help would be great thanks!

Upvotes: 1

Views: 1365

Answers (1)

Iggy
Iggy

Reputation: 4888

Consider using Camera.ScreenPointToRay.

If you're always shooting from the center of the screen you could use Camera.ViewportPointToRay

Ray ray = Camera.main.ViewportPointToRay(new Vector2(0.5f, 0.5f));

if (Physics.Raycast(ray, out RaycastHit hit, weaponRange)) // handle hit

Upvotes: 2

Related Questions