I’m creating a Unity 3D game and implementing a function where the player fires a gun.
When the player attacks with a gun, the bullet is fired forward through the Rigidbody velocity from the bullet launch position.
Bullets are fired well, but there is a problem that the character rotates every time it is fired.
(Rigidbody is applied to both player and bullets)
I think it’s a problem with Rigidbody, so can you tell me the cause and solution of this problem?
public class Weapon : MonoBehaviour
{
public enum AttackType { Melee, Range };
public AttackType type;
public int damage;
public float speed;
public BoxCollider meleeArea;
public TrailRenderer trailEffect;
public Transform bulletPosition;
public GameObject bullet;
public Transform bulletCasePosition;
public GameObject bulletCase;
public int maxAmmo;
public int currentAmmo;
public void UseWeapon()
{
if (type == AttackType.Range && currentAmmo > 0)
{
currentAmmo--;
StartCoroutine(Shot());
}
}
IEnumerator Shot()
{
// fire bullet
GameObject instantBullet = Instantiate(bullet, bulletPosition.position, bulletPosition.rotation);
Rigidbody bulletRid = instantBullet.GetComponent<Rigidbody>();
bulletRid.velocity = bulletPosition.forward * 50;
yield return null;
// bullet case
GameObject instantBulletCase = Instantiate(bulletCase, bulletCasePosition.position, bulletCasePosition.rotation);
Rigidbody bulletCaseRid = instantBulletCase.GetComponent<Rigidbody>();
Vector3 caseVector =
bulletCasePosition.forward * Random.Range(-3, -2) + bulletCasePosition.up * Random.Range(2, 3);
bulletCaseRid.AddForce(caseVector, ForceMode.Impulse);
bulletCaseRid.AddTorque(Vector3.up * 10, ForceMode.Impulse);
}
}