- Home /
Vector3.normalize not behaving as expected?
So i've got to top down 2d game. If you right click the player shoots a bullet. I make the bullet shoot by doing the following:
public virtual void shoot()
{
if(ShootingType == "normal")
{
Vector3 norm = CalculateAngle();
this.GetComponent<Rigidbody2D>().velocity = norm*BulletSpeed;
}
}
public virtual Vector3 CalculateAngle()
{
Vector3 m1 = Camera.main.ScreenToWorldPoint(Input.mousePosition);
Vector3 t1 = transform.position;
return (m1-t1).normalized;
}
And for some reason when I click far away from the player the bullet shoots fast, and when I click close to the player the bullet shoots slow... Shouldn't the bullet velocity be the same for both cases because I normalized the vector to get a magnitude of 1? I don't know why I can't figure this out, I had a similar situation awhile ago and I got it to work... Any Help?
Answer by ryan_unity · Jan 01, 2016 at 09:08 PM
m1 is a 3D vector that's pointing "into" the world:
Vector3 m1 = Camera.main.ScreenToWorldPoint(Input.mousePosition);
As you're working in 2D, you want a normalized vector in 2D space. If your camera is facing along the Z-axis then you could just set m1.z = transform.position.z inside CalculateAngle, like so:
public virtual Vector3 CalculateAngle() {
Vector3 m1 = Camera.main.ScreenToWorldPoint(Input.mousePosition);
m1.z = transform.position.z;
Vector3 t1 = transform.position;
return (m1-t1).normalized;
}
Thank you! I forgot about that z position. I ended up just changing m1 and t1's type to Vector2 ins$$anonymous$$d of Vector3 so I can keep everything in 2D. Again, thank you!