ZBLOG

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

您可以将Update函数中的IsTouchedOnPlayer函数替换为前面提到的Physics2D.OverlapPoint方法或者Physics2D.Raycast方法,来判断是否触摸到角色。具体代码如下:

void Update()
{
    if (Input.touchCount > 0) //检测是否有触摸事件发生
    {
        Touch touch = Input.GetTouch(0); //获取第一个触点的信息

        switch (touch.phase)
        {
            case TouchPhase.Began:
                Vector2 touchPosition = Camera.main.ScreenToWorldPoint(touch.position);
                Collider2D hitCollider = Physics2D.OverlapPoint(touchPosition);

                if (hitCollider != null && hitCollider.gameObject.CompareTag("Player")) //如果触摸到角色,则在角色脚下生成光圈,并返回,不进行移动操作
                    return;
                else
                    currentCircle = Instantiate(circlePrefab, transform.position, Quaternion.identity);
                break;

            case TouchPhase.Moved:
                if (currentCircle != null) //如果有光圈,则在手指移动的位置生成另外一个光圈(不移动角色)
                {
                    Vector3 touchPos = Camera.main.ScreenToWorldPoint(touch.position); //将屏幕坐标转换为世界坐标
                    touchPos.z = 0;
                    currentCircle.transform.position = touchPos;
                }
                break;

            case TouchPhase.Ended:
            case TouchPhase.Canceled:
                if (currentCircle != null)
                    Destroy(currentCircle);

                Vector2 touchPosition = Camera.main.ScreenToWorldPoint(touch.position);
                Collider2D col = GetComponent<Collider2D>();
                
                if (col == Physics2D.OverlapPoint(touchPosition)) //如果结束时还在角色身上,则直接返回,不进行移动操作
                    return;

                targetPos = touchPosition; //将屏幕坐标转换为世界坐标,作为目标位置

                if (currentCoroutine != null)
                    StopCoroutine(currentCoroutine);

                currentCoroutine = StartCoroutine(MoveToTarget());
                break;
        }
    }
}

这里的判断逻辑是:获取触摸点的世界坐标,并通过Physics2D.OverlapPoint方法获取是否有碰撞器与该点重叠。如果有,则判断该碰撞器所在的游戏对象是否具有”Player”标签,如果是,则认为触摸到了角色。如果没有重叠,则进行光圈生成和移动操作。

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

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

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

联系我们

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

微信号:3007537140

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

关注我们
x

注册

已经有帐号?