How to make player launch toward mouse position, but with a consistent velocity?
I've at least got the player to properly fling toward the mouse position with
rb2d = GetComponent<Rigidbody2D>();
void Torpedo()
{
Vector2 mousePosition = Input.mousePosition;
mousePosition = UnityEngine.Camera.main.ScreenToWorldPoint(mousePosition);
Vector2 Torpedo_Force = new Vector2(mousePosition.x - transform.position.x, mousePosition.y - transform.position.y);
rb2d.velocity = (Torpedo_Force);
}
But the problem is the amount of force added is dependent on how far the mouse is from the player. I want the amount of force to be fixed so that I can adjust the power of the launch depending on how long the mouse button is held down for before releasing. How might I be able to prevent the mouse distance from affecting the power of the launch?
Answer by highpockets · May 30, 2019 at 08:04 AM
At the moment, you are only using the magnitude/length of the directional vector. You are on the right path, but may I suggest that you normalize the direction and multiply it by the speed value you want, like so:
float torpedoForce = 20.0f;
Vector2 torpedoDirection= (mousePosition - transform.position).normalized;
rb2d.velocity = (torpedoDirection * torpedoForce);
Normalizing the vector makes it the length of 1 unit, so then multiplying the speed will make the vector length equal to speed while still facing the same direction.
Cheers