game object movement

HI everyone, I am new to Unity, so just need a simple answer of my curiosity. If there is a gameobject transform like, Position X=-2 and we are trying to move gameobject horizontally from keyboard and write following codes

`void Update()

    float horizontal = Input.GetAxis("Horizontal");
    Vector2 position = transform.position;
    position.x = position.x + 0.1f * horizontal;
    transform.position = position;

If the game object is not moving at start and has transform position showing on inspector like position x-axis=-2 then, the variable horizontal get value 0 not -2, why? I was expecting that when I click play button, in the code [position.x = position.x + 0.1f * horizontal;] the value of horizontal will be -2 so, it should move just after pressing a play button without the need to use keyboard to move the object but it did not work like that. The object don’t move unless pressing the right or left key button which means that the horizontal get value = 0. How is it like that?

Hi there,

The variable “horizontal” is getting the values of the Horizontal Axis.

“horizontal” will be 0 if you don’t press any key.

If you press the Positive key of the Horizontal Axis (key ‘D’ or right arrow), “horizontal” will starts increasing until it gets to 1.

If you press the Negative key of the Horizontal Axis (key ‘A’ or left arrow) , “horizontal” will starts decreasing until it gets to -1.

So, this means that “horizontal” is giving you a value depending on wether you press a key or not. It does not depend on the position of the object.

Hope it helps.