在 Unity 中通过 Mapwidth 进行钳制

Clamping by Mapwidth in Unity

对于unity中的平滑触摸,但我不知道应该在哪里使用Mathf.Clamp来限制玩家在地图中的移动。

知道了。

您可以简单地更改位置计算并添加一定的硬性限制,例如

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;
    }
}