What does dividing by Screen.width and multiplying it by screenWidthInUnits do? What is the purpose of doing this?

void Update()
{
    float mousePosInUnits = Input.mousePosition.x / Screen.width * screenWidthInUnits;
    Vector2 paddlePos = new Vector2(mousePosInUnits, transform.position.y);
    transform.position = paddlePos;
}

Hi Svetlin,

In this scenario you are converting the screen, measure in pixels, to Unity’s World Units. You are effectively stating that each Unity World Unit is equal to a number of pixels.

To give you a little example, let’s say you had a screen width of 800 pixels and that the mouse position was exactly in the middle. You would take the X value of the mouse position, which would be 400 and divide it by the screen width of 800, this results in a value of 0.5. Make sense as we are in the middle of the screen. Now, you multiple 0.5 by the screenWidthInUnits variable, let’s say this has a value of 16. The end result would be 8. So, the transform’s X axis value would then be set to 8. With a 16 Unity world unit wide play space, this would be in the middle.

Also, there’s no need to prefix your questions with [Question], the question mark on the end of the topic title indicates it is a question :slight_smile:

Hope this helps :slight_smile:

3 Likes

Privacy & Terms