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);
}
}
}