- Home /
How do I fire a bullet where my player is facing? (C# 2D)
I am making a Top Down 2D game, and I can't figure out how to fire a bullet where my player is facing. Currently the bullet only fires to the right, from my fire point. My bullet does destroy either after 3 seconds, or after hitting a wall or enemy. I am using C#
if (Input.GetKey(KeyCode.Space) && Time.time > nextFire) {
nextFire = Time.time + fireRate;
Instantiate (bullet, firePoint.position, firePoint.rotation);
GetComponent<Rigidbody2D> ().velocity = new Vector2 (speed, GetComponent<Rigidbody2D> ().velocity.y);
Destroy (GameObject.FindWithTag("Bullet"), lifeTime);
}
Answer by Reynarz · Aug 02, 2017 at 09:19 PM
Transform.Up is your friend.
public GameObject _myBulletPrefab;
public float _shootForce = 15f;
private GameObject _munitionInstance;
private void Shoot()
{
_munitionInstance = Instantiate(_myBulletPrefab);
var munitionRigidBody = _munitionInstance.GetComponent<Rigidbody2D>();
munitionRigidBody.velocity = player.transform.up * _shootForce ;
}
And for destroy it
private void DestroyMunition()
{
Destroy(_munitionInstance, 2f);
}
Answer by LocalNoob · Aug 02, 2017 at 09:15 PM
In instantiate instead of firePoint.rotation use transform.up(or whatever axis it is that is in fornt of yar character). Also Instantiate returns an instantiated object so before instantiate type GameObject bullet = Instntiate()...And destroy this bullet by its refrence not by searching it by tag! it is extremely inefficient! Also it is better to use raycasting and at last! your problem is in how u set your velocity...You should instaed set it to (transform.up*speed), your current aproach will always have it go in one direction
Thank you! This worked! Sorry, I'm going to be a freshman in High School, so I'm learning how to code on my own, I am trying to learn how to code things efficiently.
Your answer
![](https://koobas.hobune.stream/wayback/20220612131805im_/https://answers.unity.com/themes/thub/images/avi.jpg)