【问题标题】:Efficient way to detect touch except on the area of joystick除操纵杆区域外检测触摸的有效方法
【发布时间】:2021-03-16 03:09:08
【问题描述】:

我正在使用这个操纵杆和镜子来联网

https://github.com/herbou/Unity_EasyJoystick

我有这个脚本可以在用户触摸时发射子弹

public class ShootBullet : NetworkBehaviour
{
    [SerializeField]
    private GameObject bulletPrefab;
    private GameObject bullet;

    // Set via the Inspector in Units/second
    [SerializeField] private float _moveSpeed = 2f;
    [SerializeField] private Camera _camera;
    Vector3 touch_Pos = new Vector3(0, 0, 0);

    private void Awake()
    {
        if (!_camera) _camera = Camera.main;
    }

    void Update()
    {
        if (Input.touchCount > 0 && this.isLocalPlayer)
        {
            if (Input.GetTouch(0).phase == TouchPhase.Began)
            {
                var touch = Input.GetTouch(0);
                touch_Pos = _camera.ScreenToWorldPoint(touch.position);

                this.CmdShoot();
            } 
        }

        if (bullet != null)
        {
            bullet.transform.position = Vector3.MoveTowards(bullet.transform.position, touch_Pos, _moveSpeed * Time.deltaTime);
        }
        
    }

    [Command]
    void CmdShoot()
    {
        bullet = Instantiate(bulletPrefab, this.transform.position, Quaternion.identity);
        NetworkServer.Spawn(bullet);
    }

}

我现在的问题是当我触摸操纵杆区域时它会发射子弹。在操纵杆区域排除 input.touch 的有效方法是什么

【问题讨论】:

    标签: unity3d


    【解决方案1】:

    您可以对触摸位置进行光线投射并检查结果。

    var mousePos = Input.mousePosition;
    var mouseToRay = _camera.ScreenPointToRay(mousePos);
    RaycastHit hit;
    if (Physics.Raycast(mouseToRay, out hit))
    {
        var gameObject = hit.collider.gameObject;
        //Here You can check the name of your object or the layer or tag
        var isMouseUnderJoyStick = gameObject.CompareTag("Your_UI_Tag");
    }
    

    你必须将碰撞器组件添加到你的操纵杆

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多