0
\$\begingroup\$

I have used pythagoras to give the bullet a velocity in the bullet class. Velocity is applied when Instantiated();

 private Rigidbody2D rB;
 private Vector2 velocity;
 private float bulletSpeed = 15f;

 rB.velocity = new Vector2(bulletSpeed * (Mathf.Cos(transform.rotation.z)), bulletSpeed * (Mathf.Sin(transform.rotation.z)));

I call the instantiation from the Gun class.

if (Input.GetButtonDown("Fire1"))
        {
            bullet = Instantiate(bullet, bulletObjectPos.transform.position, transform.rotation);           
        }

Its giving me funny velocities for the angle i shoot from when the placeholder Gameobject class is rotated, shown below:

Do i need to do more to the velocity? like conversions to radians or something? Or is doing the Pythagoras thing all wrong. I've been scouring the internet all day.Thanks for any help.

The 'Bullets' travel from the muzzle to their location on the images

Shot 1

Shot 2

Shot 3

Shot 4

\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

transform.rotation is a Quaternion, not a collection of angles. Accessing individual components of a quaternion is almost never what you want to do.

Instead, you can do something like....

 // Implicit conversion to Vector2 strips out the z component.
 Vector2 firingDirection = transform.right;
 firingDirection = firingDirection.normalized;

 Vector2 velocity = speed * firingDirection;
\$\endgroup\$
2
  • \$\begingroup\$ Thank you! Are you setting firingDirection.z to 0 just as a initial assignement?Also what is the difference between .normalised and the Normalize? Dont they both do the same thing? \$\endgroup\$
    – Lonchenzo
    Commented Dec 20, 2018 at 18:03
  • \$\begingroup\$ I'm zeroing-out the z to ensure the result is a unit vector in the XY plane, though we can just force it to be a 2D vector instead. I'll show that version... (And yes, .normalized is just a shortcut for Vector3.Normalize) \$\endgroup\$
    – DMGregory
    Commented Dec 20, 2018 at 18:31

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .