Adding force to a rigidbody from angle

I am trying to implement some mouse controls into my game that mimic that of a “swipe” on an iPhone. Here is my code:

void Update () {
		if(Input.GetMouseButtonDown(0))
        	_startPos = Input.mousePosition;
		
		if(Input.GetMouseButtonUp(0))
		{
			_endPos = Input.mousePosition;
			CalculateVelocity();
		}
	}
	
	void CalculateVelocity() {
		// Calculate the angle of the swipe
		_angle = Vector3.Angle(_endPos - _startPos, Vector3.down);
		_angle = Mathf.Clamp(_angle, 0, 75);
		
		// Calculate the power of the swipe
		_force = Mathf.Clamp((_startPos - _endPos).sqrMagnitude / 100, 1f, 1000f);
	}

As you can see, I am using the MouseDown and MouseUp positions to figure out a force value (based on the length of the line they dragged) and the angle of the line.

I want to apply the force value to my player based on the angle the player draws. So, if the user clicks and drags the mouse right at an angle of 50 degrees, how would I then AddForce so the rigidbody moves left at the same angle?

It’s almost as if the mouse is a catapult and clicking and dragging anywhere on the screen can apply force to the player.

Supposing your game’s “ground” is the XZ plane (Y is the vertical direction) and that you have a vector in the target direction (let’s call it targetDir), you can do this:

    var force: Vector3 = targetDir;
    force.y = 0; // zero y to keep hor direction only
    force.Normalize(); // normalize horizontal direction
    force.y = Mathf.Sin(_angle * Mathf.Deg2Rad); // set elevation
    // vector force now points to the target at _angle degrees from the ground
    rigidbody.AddForce(force.normalized * _force);

When shooting, it’s easier to set the rigidbody velocity instead of using AddForce - a force increases the velocity depending on mass, force intensity and time, so it’s much more complicated to control. To try this approach, just change the last line to:

    rigidbody.velocity = force.normalized * _force;