为了限制光圈的移动范围,你可以在HandleTouchMoved()函数中添加以下代码:
获取触摸位置的世界坐标,使用Camera.main.ScreenToWorldPoint()方法将屏幕坐标转换为世界坐标。
将光圈位置限制在某个矩形区域内。你可以定义一个Rect类型的变量来表示这个区域,并在Start()函数中初始化它。
在HandleTouchMoved()函数中检查当前光圈是否超出了限制区域。如果超出了,则将其位置调整到最近的边界上。
以下是修改后的代码示例:
public class PlayerController1 : MonoBehaviour {
public GameObject circlePrefab;
private GameObject currentCircle;
private Vector3 targetPosition;
private bool facingRight = true;
Coroutine currentCoroutine;
// 定义限制范围
private Rect bounds = new Rect(-4f, -2f, 8f, 4f);
void Start()
{
// 确保左下角和右上角的点都在bounds内
Vector3 min = new Vector3(bounds.xMin, bounds.yMin);
Vector3 max = new Vector3(bounds.xMax, bounds.yMax);
min = Camera.main.ViewportToWorldPoint(min);
max = Camera.main.ViewportToWorldPoint(max);
bounds.SetMinMax(min, max);
}
void Update()
{
if (Input.touchCount > 0)
{
Touch touch = Input.GetTouch(0);
switch (touch.phase)
{
case TouchPhase.Began:
if (IsTouchedOnPlayer(touch.position))
{
currentCircle = Instantiate(circlePrefab, transform.position, Quaternion.identity);
return;
}
break;
case TouchPhase.Moved:
if (currentCircle != null)
{
Vector3 touchPos = Camera.main.ScreenToWorldPoint(touch.position);
touchPos.z = 0;
// 将光圈位置限制在bounds内
touchPos.x = Mathf.Clamp(touchPos.x, bounds.xMin, bounds.xMax);
touchPos.y = Mathf.Clamp(touchPos.y, bounds.yMin, bounds.yMax);
currentCircle.transform.position = touchPos;
}
break;
case TouchPhase.Ended:
if (currentCircle != null)
{
HandleTouchEndedOrCanceled(touch);
Destroy(currentCircle);
}
break;
case TouchPhase.Canceled:
break;
}
}
}
// 其他函数不变
}
这样,光圈就只能在指定的矩形区域内移动了。