Input.mousePosition.x is not working properly I cant't find the reason

Viewed 28
private void FixedUpdate()
{
    if (Input.GetMouseButton(0) || isStart)
    {
        isStart = true;
        transform.Translate(new Vector3(Input.mousePosition.x * Time.fixedDeltaTime * 0.05f, 0, speed * Time.fixedDeltaTime));
    }
}

When the game starts, when I click left on the screen, the object moves to the right instead of to the left. When I right click, it goes right again, but faster. As far as I understand, it considers the leftmost part of the screen as the middle, but why?

enter image description here

1 Answers

Input.mousePosition.x is a value that goes from 0 (leftmost) to Screen.width (rightmost) - see more on documentation.

This means that when you click on the left side your value is lower than when you click on the right side, this explains the speed change.

The range [0. Scree.width] is always positive, which means that your movement will always be in the same direction, this explains the object goes just to one side.

A simple solution is to divide your Screen.width by 2 and create a direction based on it.

var direction = Input.mousePosition.x < (Screen.width * .5f) ? -1 : 1;
transform.Translate(new Vector3(direction * speed * Time.fixedDeltaTime, 0, speed * Time.fixedDeltaTime));
Related