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.
- 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?
- 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.