Limit swipe force between 2 float for joystick
Hello guys,
I am trying to set up joystick for projectile motion but since joystick gap is so small how can I set min and max value between swipe in joystick ?
This is how I get points and add force to rigidbody :
pointA = Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, Camera.main.transform.position.z));
pointB = Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, Camera.main.transform.position.z));
Vector2 offset = pointA - pointB; Vector2 direction = Vector2.ClampMagnitude(offset, 1.0f);
rigidbody2D.AddForce(direction.normalized * forceMagnitude, ForceMode2D.Impulse);
As I said since the max gap is small in joystick it doesnt even move with that swipe
so I am trying to keep gap same but I want to put min start and max point for example between 10 to 30
Answer by streeetwalker · Apr 04, 2020 at 08:00 AM
Hi @MagisterTerran, it sounds like you need a simple mapping function. You need to know the maximum swipe that you can have, and the maximum output range you want. Filter the input for the minimum value and don't clamp at all because the mapping function will limit the output.
The mapping function:
(currentInput - minInput)/(maxInput - minInput)*(maxOutput - minOutput)+ minOutput
We want to know how to map our input to the range 10 to 30. We should be able to find the maximum Input, because that will be the maximum swipe area. For minimum input you can just guess and try it, and make it larger or smaller from there.
To test, output range is 30 - 10, maximum swipe is 100, and our desired minimum swipe is 25 we plug in the values and solve for to get the output force value. (once you know max and min input, you can shortcut the calculation below) So in code:
// you got your offset and direction before this...
float minInput = 25;
float maxInput = 100;
If( offset.magnitude >= minInput ) {
float force = ( offset.magnitude - minInput ) / ( maxInput - minInput ) * 20 + 10;
rigidbody2D.AddForce(direction.normalized * force, ForceMode2D.Impulse);
}
Your answer
![](https://koobas.hobune.stream/wayback/20220612230452im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Weired physics behavior when launching a Ball 0 Answers
Bullet not moving rigidbody2d,AddForce not working for bullet 1 Answer
Using both RB Velocity and AddForce? 1 Answer
rigid.velocity.x = 0 for unknow reason 0 Answers
2d side scroller car racing game, can't manage to understand swipe down to forcefully land on ground 0 Answers