# My bullet changes the velocity depending on where I click

I want to build a little 2D-Sidescrolling shooter and I'm now at the shooting script.

I already figured out how to shoot a bullet towards my mouse pointer. I got something like this :

Vector3 shootDirection;
shootDirection = Input.mousePosition;
shootDirection.z = 0.0f;
shootDirection = Camera.main.ScreenToWorldPoint (shootDirection);
shootDirection = shootDirection - transform.position;

shootDirection.Normalize ();

Rigidbody2D bulletInstance = Instantiate (rocket, transform.position, Quaternion.identity) as Rigidbody2D;
bulletInstance.velocity = new Vector2 (shootDirection.x * speed, shootDirection.y * speed);


Now obviously the bullet goes faster if my Direction coordinates are big and slower if they are smaller. Have you some better code for me or how can I fix that issue?

I added now some loop like this, which brings a horrible performance, but kinda works out for the problem, but I'm still looking for a better solution.

while (((shootDirection.x * speed) + (shootDirection.y * speed)) < 20) {
speed += 0.1f;
}


So the loop makes sure that the overall speed is always almost the same, but this solution ends in an infinity loop if the values get too small.

• Is transform.position also fixed at 0.0f on the Z axis? If not, this will affect the Normalize function. Jul 27, 2015 at 15:53
• Mhm I don't know about that, but how would that affect the bullet? Can I see that visualy? Jul 27, 2015 at 17:03
• Nevermind I fixed that and I don't think that it changed anything. Jul 27, 2015 at 17:05
• "Now obviously the bullet goes faster if my Direction coordinates are big and slower if they are smaller." Are you sure? Why is it that obvious? Your call to shootDirection.Normalize(); should take care of this, shouldn't it? Jul 27, 2015 at 19:16
• Normalize makes everything the same length, so after that points far away and close by have the same "size". At that point, you should just be able to do shootDirection * 20.0 (instead of your loop - speed will always be 20) to get the actual distance traveled for a projectile per unit time. If you're ignoring z, though, why aren't you using a 2D vector? Jul 28, 2015 at 13:01

        Vector2 target = Camera.main.ScreenToWorldPoint (new Vector2 (Input.mousePosition.x, Input.mousePosition.y));