简体   繁体   English

在 Unity 中按 Mapwidth 进行钳位

[英]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.为了统一的平滑触摸,但我不知道应该在哪里使用 Mathf.Clamp 来限制 map 中玩家的移动。

Got It.知道了。

You can simply change the position calculation and add a certain hard limit like eg您可以简单地更改 position 计算并添加一定的硬限制,例如

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM