I’ve started to add different guns to my game, most recently a shot gun, up until recently I’ve been using raycasts to detect if I’m shooting something, which is fine for most guns, but I wanted the Shotgun to have more of a spread, so you don’t have to be as accurate, so I looked up how I could somehow widen a Raycast, I’ve found out about the Capsule Cast, which can do exactly what I wanted.
I’m having problems using it though, with some guns, it works great, but with others, the accuracy’s way off, way above or below the crosshair.
Here’s my code:
shooting = true;
RaycastHit hit;
Vector3 directionRay = gunMuzzle.TransformDirection(Vector3.forward);
//Vector3 capsulePoint2 = gunMuzzle.position + directionRay;
Debug.DrawRay (gunMuzzle.position, directionRay * range, Color.red);
if (bulletsLeft > 0 || isMeleeWeapon)
{
if (Physics.SphereCast(gunMuzzle.position, spread, directionRay, out hit, range))
{
if (hit.rigidbody)
{
if (hitParticle)
{
hitParticle.transform.position = hit.point;
hitParticle.transform.localRotation = Quaternion.FromToRotation(Vector3.forward,
hit.normal);
hitParticle.Emit();
}
hit.rigidbody.AddForceAtPosition(directionRay * force, hit.point);
hit.collider.SendMessageUpwards("ApplyDamage", damage, SendMessageOptions.DontRequireReceiver);
if (isMeleeWeapon)
{
audio.PlayOneShot(reloadSound);
}
}
else if (hit.collider.gameObject.CompareTag("Kruncanite"))
{
if (!bloodEffect)
{
bloodEffect.transform.position = hit.point;
bloodEffect.transform.localRotation = Quaternion.FromToRotation(Vector3.forward, hit.normal);
bloodEffect.Emit();
}
}
}
What am I doing wrong?