- Home /
Changing the horizontal movement direction of the player
Hello everyone,
I am using in FixedUpdate() function the Input.GetMouseButtonDown() method. I want my player to change the horizontal direction, so for this I have the following code:
if (Input.GetMouseButtonDown(0))
{
if(change == true)
{
rb.velocity = new Vector2(-12,rb.velocity.y);
change=!change;
}
else if(change == false)
{
change=!change;
rb.velocity = new Vector2(12,rb.velocity.y);
}
}
At the beginning, first 3-6 clicks, works fine (one click change direction, another click the other direction) but afterwards I have to press 2 or 3 times to change the actual direction.
What should I do to increase the accuracy, quality of changing directions?
Thank you very much for your patience and attention!
Have you tried just Update() ins$$anonymous$$d of FixedUpdate()?
Yes, that was the issue, thank you very very much sir!
Answer by Vega4Life · Jul 31, 2019 at 03:54 PM
Like @I_Am_Err00r mentioned, you will for sure miss mouse clicks looking for input in the Fixed Update. You can put your input in Update, but leave your movement in Fixed (since you are moving via rb velocity). Something like this (I also made the direction more simplified):
[SerializeField] float moveDistance = 12;
Rigidbody rb;
bool changeDirection;
int currentDirection = 1;
private void Awake()
{
rb = GetComponent<Rigidbody>();
}
private void Update()
{
if (Input.GetMouseButtonDown(0))
{
changeDirection = true;
}
}
private void FixedUpdate()
{
if (changeDirection)
{
rb.velocity = new Vector3(currentDirection * moveDistance, rb.velocity.y);
currentDirection *= -1;
changeDirection = false;
}
}
Your answer
![](https://koobas.hobune.stream/wayback/20220612205815im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Combining 2 Vectors for Diagonal Movement 1 Answer
Rotation too complicated 3 Answers
Rolling ball with Horizontal Input 1 Answer
How can I make my character jump & move him by zone 0 Answers