问题描述
为了统一的平滑触摸,但我不知道我应该在哪里使用 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,maxX);
transform.position = currentPosition;
}
}