Clamping from Sprite Size

I came up with a solution that finds the boundaries of the Paddle’s sprite and uses those to calculate the clamping values you need to use. This means you can update the clamping programmatically in Update() if, for example, you changed the size of the paddle Sprite with a power-up. I wondered if the way I’ve gone about this is the most efficient or if there’s a better way?

Code is below:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PaddleController : MonoBehaviour
{
    [SerializeField] private float screenWidthInWorldUnits = 16f;

    private float xMin = 0f;
    private float xMax = 16f;

    private SpriteRenderer paddleSpriteRenderer;

    // Start is called before the first frame update
    void Start()
    {
        paddleSpriteRenderer = this.GetComponent<SpriteRenderer>();
    }

    // Update is called once per frame
    void Update()
    {
        // find the size of the paddle's sprite to determine screen clamping
        // this is useful because if the sprite is updated (for example the paddle got bigger)
        // it will still be properly clamped to the screen
        xMin = 0f + paddleSpriteRenderer.sprite.bounds.size.x / 2;
        xMax = screenWidthInWorldUnits - paddleSpriteRenderer.sprite.bounds.size.x / 2;

        // work out mouse position to world position
        float xMousePos = (Input.mousePosition.x / Screen.width) * screenWidthInWorldUnits;
        Vector2 paddlePos = new Vector2(xMousePos, transform.position.y);

        // clamp the paddle position to the screen
        paddlePos.x = Mathf.Clamp(xMousePos, xMin, xMax);

        transform.position = paddlePos;
    }
}

I also do it in similar manner mate!
In our solution we can’t limit the paddle min/max X, cause we don’t serialize it. Anyway we can add some check if serialize field is empty, than use calculated props.

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Paddle : MonoBehaviour
{
    float cameraWidth;
    float paddleHalfWidth;
    float paddleMinX;
    float paddleMaxX;
    // Start is called before the first frame update
    void Start()
    {
        cameraWidth = (float)Math.Round(Camera.main.orthographicSize * Camera.main.aspect) * 2;
        paddleHalfWidth = GetComponent<SpriteRenderer>().bounds.size.x / 2;
        paddleMinX = paddleHalfWidth;
        paddleMaxX = cameraWidth - paddleHalfWidth;
    }

    // Update is called once per frame
    void Update()
    {
        float currentMouseXPos = Input.mousePosition.x / Screen.width * cameraWidth;
        float newPaddleXPos = Mathf.Clamp(currentMouseXPos, paddleMinX, paddleMaxX);
        Vector2 paddlePos = new Vector2(newPaddleXPos, transform.position.y);
        transform.position = paddlePos;
    }
}
1 Like

Privacy & Terms