- Home /
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.
Code: { 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;
Shoot();
}
}
void Shoot()
{
Vector3 rayOrigin = playerCam.ViewportToWorldPoint(new Vector3(0.5f, 0.5f, 0.0f));
muzzleFlash.Play();
RaycastHit hit;
if (Physics.Raycast(rayOrigin, playerCam.transform.forward, out hit, range))
{
Debug.Log(hit.transform.name);
Enemy enemy = hit.transform.GetComponent<Enemy>();
if (enemy != null)
{
enemy.TakeDamage(damage);
}
GameObject impactGO = Instantiate(impactEffect, hit.point, Quaternion.LookRotation(hit.normal));
Destroy(impactGO, 2f);
}
}
}
Answer by pmerilainen · Jul 11, 2019 at 09:31 AM
you could try to replace zero z with camera.nearClipPlane
How would I implement that into my code? I really only somewhat know the very basics
playerCam.ViewportToWorldPoint(new Vector3(0.5f, 0.5f, playerCam.nearClipPlane))
I've just added that to my script. Seems to be working so far. Thanks :)
God. This is both annoying and slightly embarrassing. Opened up unity after about 5 hours. Shooting works fine now?
Answer by Bunny83 · Jul 11, 2019 at 11:03 AM
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.
Your answer
![](https://koobas.hobune.stream/wayback/20220612204708im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Raycast and First Person Controller 2 Answers
Can't find a clone object with RayCast? [Solved] 2 Answers
How can I differentiate between colliding with an object or its child? 1 Answer
raycast in direction of movement key down 2 Answers
RaycastHit returns object without collider, in wrong layer 1 Answer