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.
transform.position
also fixed at 0.0f on the Z axis? If not, this will affect the Normalize function. \$\endgroup\$shootDirection.Normalize();
should take care of this, shouldn't it? \$\endgroup\$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 doshootDirection * 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 ignoringz
, though, why aren't you using a 2D vector? \$\endgroup\$