My solution. Am I overthinking things?

So this is my Paddle code:

public class Paddle : MonoBehaviour
{
    private Vector2 paddlePosition;

    private float minX;
    private float maxX;

    private void Start()
    {
        float halfSizeX = GetComponent<Renderer>().bounds.extents.x;
        minX = 0f + halfSizeX;
        maxX = Camera.main.ScreenToWorldPoint(new Vector3(Screen.width, 0f)).x - halfSizeX;
        paddlePosition = new Vector2(transform.position.x, transform.position.y);        
    }

    void Update()
    {
        float mousePositionX = Camera.main.ScreenToWorldPoint(Input.mousePosition).x;

        paddlePosition.x = Mathf.Clamp(mousePositionX, minX, maxX);
        
        transform.position = paddlePosition;
    }
}

This works fine but I do have some questions.

  1. Is there no way to set a single axis in a transform without creating a new Vector2/3 object? Isn’t that a performance overhead to create a new instance of an object and discard it each frame?
  2. I decided to get the clamp limits by using the size of the rendered object. Calling GetComponent<Renderer>().bounds.extents.x gave me the result 1 which does correspond to half the size of the paddle in world units. My question here is this a happy coincidence? I thought that the value of the bounds will be in pixels, not in world units.

Hi Matija,

Welcome to our community, and thank you for your questions! :slight_smile:

  1. There isn’t because transform.position is not a variable but a property. You cannot edit its values.
  2. It’s not a happy coincidence. In the scene (apart from the Canvas and its UI-elements), Unity works with World Units (WU). The sprite gets rendered onto a box whose size is defined in WU. Maybe you remember that you changed the Pixels Per Units (PPU) value of the sprite at some point. And “Units” refers to “World Units”.

Did this help?


See also:

I see. That’s interesting! I thought that WU would apply to everything except rendering component but it does make sense that everything is in WU and then I assume that the rendering system internally converts WU to pixels or something. Thanks for the answer, very helpful.

That’s very likely happening because, in the end, the sprites and textures end up on our physical screens which consist of physical pixels (and other things).

However, the 3D world inside Unity is huge. When you zoom out, the sprites on your screen shrink while their actual size (in WU) remains the same. Just like in the real world: If we know that our friend is 1.80 m tall but see them from far away, we would not think they were suddenly 1.80 cm tall. We still consider them as 1.80 m. There are two systems: One are the dimensions relative to our own point of view, and one are the dimensions relative to something else.

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms