- Home /
Top Down Shooting Not Working
I am making a 2D, top down shooter. I am trying to make the bullets go towards the mouse. I already have the player pointing in the direction of the mouse, but when I try to fire the bullets, transform.forward doesn't want to work. If I used anything else, like transform.right, the bullets move right. Something about my transform.forward doesn't want to work. Here's my code.
public class BulletController : MonoBehaviour
{
public Rigidbody2D rb;
public float bulletSpeed;
// Start is called before the first frame update
void Start()
{
rb.velocity = transform.forward * bulletSpeed;
}
}
Any help with this would be greatly appreciated! Thanks!
We need more information on that, because "doesn't want to work" can mean anything - from crashing to moving in wrong direction. What exactly happening and how do you instantiate your bullets or do you pooling them from pooler? Also would be helpful if you can do an screenshot of your bullet axis, because you simply can have your forward axis pointing down, but right still be correct right that's why other directions can work correctly while forward no, at least now it seems most probable thing.
Answer by Z-ion · Jul 14, 2019 at 03:40 AM
Here is the code
public class BulletController : MonoBehaviour
{
public gamepbject bulletPrefab;
public transform bulletSpawnPosition;
public float bulletSpeed;
void Start()
{
if(Input.GetMouseDown(0))
Shoot();
}
void Shoot()
{
GameObject bullet = Instantiate(bulletPrefab,bulletSpawnPosition, Quaternion.identity);
Rigidbody2D rb = bullet.GetComponent<Rigidbody2D>();
rb.velocity = transform.forward * bulletSpeed;
}
}
You should attach this script to Player. The script you told was not working because when you spawn the bullet it’s rotation is zero because of Quaternion.identity and when you try to add velocity relative to bullet it doesn’t work as intended. So you should add velocity when you are instantiate and add the velocity relative to the player.
I hope this help you out.