Manan Parikh
Manan Parikh

Reputation: 27

Clamping by Mapwidth in Unity

For Smooth touch in unity but i dont know where should i use Mathf.Clamp to restrict the movement of player in the map.

Got It.

Upvotes: 0

Views: 114

Answers (1)

derHugo
derHugo

Reputation: 90852

You can simply change the position calculation and add a certain hard limit like e.g.

public float minX;
public float minY;
public float maxX;
public float maxY;

public float playerSpeed;

[SerializeField] private Camera _mainCamera;

void Awake()
{
    if(!_mainCamera) _mainCamera = Camera.main;
}

void Update()
{
    if (Input.touchCount > 0)
    {
        var touch = Input.GetTouch(0);
        var touchPosition = touch.position;

        var currentPosition = transform.position;
        var speed = playerSpeed * Time.deltaTime;

        // get this objects position in screen (pixel) space
        var screenPosition = _mainCamera.WorldToScreenPoint(transform.position);

        if (touchPosition.x < screenPosition.x)
        {
            currentPosition.x -= speed;
        }
        else if (touchPosition.x > screenPosition.x)
        {
            currentPosition.x += speed;
        }

        currentPosition.x = Mathf.Clamp(currentPosition.x, minX, maxX);

        if (touchPosition.y < screenPosition.y)
        {
            currentPosition.y -= speed;
        }
        else if (touchPosition.y > screenPosition.y)
        {
            currentPosition.y += speed;
        }

        currentPosition.y = Mathf.Clamp(currentPosition.y, minX, maxX);

        transform.position = currentPosition;
    }
}

Upvotes: 1

Related Questions