简体   繁体   中英

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.

You can simply change the position calculation and add a certain hard limit like eg

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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