2d Game - Fire projectile at correct angle

Hey all,

I’m having trouble with the math involved in getting a projectile to fire at a constant speed in the direction a game object is facing. Like shooting a turret.

I can’t seem to get it to work. Not sure what to work with either eg degrees or radians. Here is what I have tried.

GameObject bullet = (GameObject) Instantiate(bulletPrefab, nozzel.transform.position, Quaternion.identity);
				
float turretAngle = turret.transform.localRotation.z;
float bulletAngle = (turretAngle * 180 / Mathf.PI);

float bulletSpeed = 2;
			
float ax = Mathf.Cos(bulletAngle) * bulletSpeed;
float ay = Mathf.Sin(bulletAngle) * bulletSpeed;
				
Vector3 bulletForce = new Vector3(ax,ay,0);
bullet.rigidbody.velocity = bulletForce;

It seems to move at the correct speed just not the correct direction. Also I have setup my turret sprite a little weird I need to subtract 90 degrees of the angle.

EDIT: Also I just had a quick thought to I need to multiply something by time.deltatime ? so that the slower fps moves correctly?

Thanks for any help

no, no deltaTime is needed here.

A simpler way would be to just get the Vector that the turret is aing and use that, ignoring angles.

Assuming your turret’s forward is the way you want to bullet to go:
Vector3 bulletForce = turrent.forward * bulletSpeed;
bullet.rigidbody.velocity = bulletForce;

Thanks pakfront, that looks simple enough. I’ll give it a shot tonight.

Quick question, I’m certain my turrets sprite isn’t facing in the forward direction. Is it impossible to rotate the z direction of a vector?

EDIT: Or would it just be easier to edit my sprite so it is facing the forward direction?

I would do that. You’ll save yourself other headaches later.

Yeah I thought so. Guess I gotta load the good old photoshop and flip this sprite :slight_smile: