Raycast not hitting right spot

I’ve got a problem with a game I started making.
Basically every time I shoot, the particle effect which essentially shows where the raycast is hitting, isn’t where my crosshair is pointing. My crosshair is in the center of the screen.
Sometimes it’ll work and hit the center.
When I try to attach a photo it says “Error parsing the uploaded file.”, but basically the ray ends up either hitting a meter or two diagonally left of wherever I’m shooting or on top of the object I’m trying to shoot. Tried messing around with ViewportToWorldPoint. Hasn’t made a difference

Btw, pretty damn new at this.

public float damage = 10f;
public float range = 10f;
public float fireRate = .5f;
private float nextFire;

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

public GameObject crosshair;

void Update()
    if (Input.GetButtonDown("Fire1") && Time.time > nextFire)
        nextFire = Time.time + fireRate;


void Shoot()
    Vector3 rayOrigin = playerCam.ViewportToWorldPoint(new Vector3(0.5f, 0.5f, 0.0f));

    RaycastHit hit;
    if (Physics.Raycast(rayOrigin, playerCam.transform.forward, out hit, range))

        Enemy enemy = hit.transform.GetComponent<Enemy>();

        if (enemy != null)

        GameObject impactGO = Instantiate(impactEffect, hit.point, Quaternion.LookRotation(hit.normal));
        Destroy(impactGO, 2f);


you could try to replace zero z with camera.nearClipPlane

Your whole ViewportToWorldPoint is pointless when you use a perspective camera. Just use the camera position as origin. As for the direction, only the center point will be transform.forward for a perspective camera. It’s generally simpler to use Camera.ViewportPointToRay to get a ray for a certain viewport point. For perspective cameras, viewport points off center will have a different direction than transform.forward. Of course for orthographic cameras all rays are parallel.