Home > Software design >  Shoot from gun in top down shooter Unity3D
Shoot from gun in top down shooter Unity3D

Time:05-19

Currently I made bullet shoot from players position. Problem is that it shoots from player's center and not from the gun. I changed position of the bullet to make it shoot out from the gun. But the problem is that, when I start to rotate the player, bullet copies the rotation but not the position of the gun. It just stays on the same place. Here's my code:

public Transform firePoint;
public GameObject bulletPrefab;
public float bulletForce = 20f;

public void Shoot()
{
    Vector3 newPosition = new Vector3(firePoint.position.x   1, firePoint.position.y - 0.1f, firePoint.position.z);
    GameObject bullet = Instantiate(bulletPrefab, newPosition, firePoint.rotation);
    Rigidbody2D rb = bullet.GetComponent<Rigidbody2D>();
    rb.AddForce(firePoint.right * bulletForce, ForceMode2D.Impulse);
    yield return new WaitForSeconds(0.5f);
}

CodePudding user response:

Your issue is that you have hard-coded offset (x = 1, y = -0.1f) change. When you rotate your player 90 degrees, the offset for gun end becomes different.

There are two solutions for this:

Solution #1

Place your fire point Transform at the tip of the gun, make it child of the gun. That way the Transform will always follow the end of the gun.

Now, for instantiating, you can use firepoint.position without any modifications.

There are some drawbacks to this, mainly having strict objects hierarchy and it becomes harder to dynamically change guns as you will have to find and reassign fire point for each of them.

Solution #2

Have Vector3 firePointOffset;.

Once instantiating, calcualte the position of the fire point by doing

var firePointPosition = playerTransform.position   Vector3.Scale(playerTransform.forward, firePointOffset)`;

transform.forward returns Vector3 that points, well, forward for that specific transform. Vector3.Scale allows multiplying two vectors x * x, y * y, z * z;

  • Related