Hello everyone,
I’ve gone through quite a few different posts about how to shoot a bullet out of a gun in a 2D environment, but believe it or not I can’t find the answer for my specific situation.
I’ve got a gun at the top of the screen that you can swivel left and right and shoot a bullet from. However, I have no idea how to get it to shoot in the direction I need it to.
Here’s my code, which isn’t right, it just shoots the bullet to the right because I’m adding positive 5. I guess I can do a check to see what the Z rotation is of the gun and based on that fire the bullet with a negative or positive force in the X direction…but it really needs to go down where the gun’s local Y is pointing…straight down it. Any suggestions are greatly appreciated.
public GameObject bullet;
public GameObject bulletSpawnPoint;
void Update () {
if (Input.GetMouseButtonDown(0))
{
bullet = (GameObject) Instantiate(bullet, bulletSpawnPoint.transform.position, Quaternion.identity);
Rigidbody2D bulletRigidBody = bullet.GetComponent<Rigidbody2D>();
bulletRigidBody.AddForce(new Vector2(bulletSpawnPoint.transform.localPosition.x + 5, 0),
ForceMode2D.Impulse);
}
}
The attached images show the little gun and the red arrow shows the direction I want the bullet to shoot out of. I do have a bulletSpawnPoint at the end of the gun, just a small sprite without the sprite showing, where the bullet properly comes out from. But from there I’m pretty lost.