Projectile speed dependent of direction vector length?

Hi everyone,
I have a question regarding my bullet speed. I’ve made a fire method which will trigger on mouseclick.

``````public void Fire()
{
GameObject projec = Instantiate(proj, gunpoint.transform.position, gunpoint.transform.rotation) as GameObject; //Instaniate bullet
Ray ray = playerCamera.ScreenPointToRay(Input.mousePosition); //get point by ray
Vector2 dir = (ray.origin - transform.position).normalized; //Get vector direction between player and mousepoint clicked
projec.GetComponent<Rigidbody2D>().velocity = projectile.speed * dir * Time.deltaTime; //Set projectile velocitymoving in direction vector with speed from other projectile script.
}
``````

However, when clicking close to the player, the direction vector becomes small → slow speed of projectiles.

If clicking with a greater distance from the player, the distance vector becomes greater and the projectiles travels faster.

Have I interpreted this correctly? How would you guys handle firing a projectile from a gunpoint rotating around the player against a mouse point?

Thank you all
Jonathan

Are you sure that’s really the code that executes (forgot to save the recent changes)? The “normalized” at the end of this line:

``````Vector2 dir = (ray.origin - transform.position).normalized;
``````

will make the vector always have a length of “1.0”. So what you describe would happen when you don’t have that “normalized” at the end.

ps: You should remove that Time.deltaTime from your that line:

``````projec.GetComponent<Rigidbody2D>().velocity = projectile.speed * dir * Time.deltaTime;
``````

It makes no sense. The velocity is a property / state of the rigidbody. You only need to multiply be deltaTime when you have any additive process that is executed every frame. You set the speed once and the speed should be constant.

edit

I just saw where your problem might come from. ray.origin and transform.position are Vector3 values. That means the subtraction of the two will result in a Vector3. You then normalize the vector3 and finally assign it to a vector3 variable. So the conversion from Vector3 to Vector2 happens at the very end. If your vectors have any difference in the z direction that would be accounted for as well when normalizing. However when you do the V3 → V2 conversion this amount is no longer present.

To fix this you can do this:

``````Vector2 dir = ((Vector2)ray.origin - (Vector2)transform.position).normalized;
``````

or this:

``````Vector2 dir = (ray.origin - transform.position);
dir.Normalize(); // or dir = dir.normalized;
``````