ZBLOG

using UnityEngine; using System.Collections; public class PlayerController1 : MonoBehaviour { public GameObject circlePrefab; // 光圈预制体,需要提前准备好 private GameObject currentCircle; // 当前生成的光圈 private Vector3 targetPosition; // 目标位置 pr...

为了限制光圈的移动范围,你可以在HandleTouchMoved()函数中添加以下代码:

  1. 获取触摸位置的世界坐标,使用Camera.main.ScreenToWorldPoint()方法将屏幕坐标转换为世界坐标。

  2. 将光圈位置限制在某个矩形区域内。你可以定义一个Rect类型的变量来表示这个区域,并在Start()函数中初始化它。

  3. 在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;
        }
    }
}

// 其他函数不变

}

这样,光圈就只能在指定的矩形区域内移动了。

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:https://sdn.0voice.com/?id=1125

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?