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.