VRTK_HeadsetCollision脚本简析(VRTK_v3.3.0版)

表示头盔显示器与有效几何体碰撞的类。

VRTK_HeadsetCollision_UnityEvents 类

在VRTK_HeadsetCollision对象中添加VRTK_HeadsetCollision_UnityEvents组件,可以访问UnityEvents,它对类事件的反应是相同的。
所有c#委托事件都映射到一个带有On前缀的Unity事件。MyEvent -> OnMyEvent。

结构体:

HeadsetCollisionEventArgs 两个参数

Collider:头盔碰到物体对象的碰撞器
Transform:挂有HeadsetCollisionFade脚本组建的对象,即Camera的Transform

委托:

public delegate void HeadsetCollisionEventHandler(object sender, HeadsetCollisionEventArgs e);

object:当前object;
HeadsetCollisionEventArgs: 上述结构体

字段

bool ignoreTriggerColliders 如果勾选此项,则头盔碰撞将忽略设置为'is Trigger = true 的碰撞器;
float colliderRadius 自动生成的球体对撞机的半径,用于检测头盔上的碰撞;
VRTK_PolicyList targetListPolicy VRTK_PolicyList类,用于确定头盔碰撞是否对任何对象都起作用;
bool headsetColliding = false; 确定眼镜当前是否与另一个对象发生碰撞
public Collider collidingWith = null; 存储眼镜与之碰撞的对撞器
protected Transform headset;//头盔
protected VRTK_HeadsetCollider headsetColliderScript;//类
protected GameObject headsetColliderContainer;// 眼镜容器
protected bool generateCollider = false; 是否生成Collider
protected bool generateRigidbody = false; 是否生成Rigidbody

事件

对应上述委托
public event HeadsetCollisionEventHandler HeadsetCollisionDetect; 当用户的头盔与另一个游戏对象碰撞时发出。
public event HeadsetCollisionEventHandler HeadsetCollisionEnded;当用户的耳机停止与游戏对象碰撞时发出。

方法

OnHeadsetCollisionDetect(HeadsetCollisionEventArgs e) 处理碰撞时事件
OnHeadsetCollisionEnded(HeadsetCollisionEventArgs e)处理停止碰撞事件
public virtual bool IsColliding() 返回是否正在碰撞
public virtual GameObject GetHeadsetColliderContainer() 返回头盔带有碰撞组建的自动生成的gameobject

Awake() 调用VRTK_SDKManager类的一个添加方法
OnEnable() 对headset赋值;不为空时对headsetColliding设置为false,调用SetupHeadset()方法
VRTK_PlayerObject.SetPlayerObject 方法

OnDisable()
调用VRTK_HeadsetCollider 类里的EndCollision方法 自身的TearDownHeadset方法;
OnDestroy() 调用VRTK_SDKManager类的一个移除方法
Update() headsetColliderContainer设置
CreateHeadsetColliderContainer() SetupHeadset()方法里调用这个方法
SetupHeadset() OnEnable() 调用
TearDownHeadset() OnDisable()调用
VRTK_HeadsetCollider类

字段

VRTK_HeadsetCollision parent 上述类
VRTK_PolicyList targetListPolicy

方法

SetParent(GameObject setParent) 设置父物体
SetIgnoreTarget() 设置忽略的碰撞组
EndCollision(Collider collider)
OnTriggerStay(Collider collider) 触发停留
OnTriggerExit(Collider collider) 触发离开
Update()
protected virtual HeadsetCollisionEventArgs SetHeadsetCollisionEvent(Collider collider, Transform currentTransform) 设置枚举值
protected virtual bool ValidTarget(Transform target) 返回bool值 检查碰到目标后是否需要谈出

// Headset Collision|Presence|70010
 namespace VRTK
  {
  using UnityEngine;

/// <summary>
/// Event Payload
/// </summary>
/// <param name="collider">The Collider of the game object the headset has collided with.</param>
/// <param name="currentTransform">The current Transform of the object that the Headset Collision Fade script is attached to (Camera).</param>
public struct HeadsetCollisionEventArgs
{
    public Collider collider;
    public Transform currentTransform;
}

/// <summary>
/// Event Payload
/// </summary>
/// <param name="sender">this object</param>
/// <param name="e"><see cref="HeadsetCollisionEventArgs"/></param>
public delegate void HeadsetCollisionEventHandler(object sender, HeadsetCollisionEventArgs e);

/// <summary>
/// Denotes when the HMD is colliding with valid geometry.
/// </summary>
/// <remarks>
/// **Script Usage:**
///  * Place the `VRTK_HeadsetCollision` script on any active scene GameObject.
/// </remarks>
/// <example>
/// `VRTK/Examples/011_Camera_HeadSetCollisionFading` has collidable walls around the play area and if the user puts their head into any of the walls then the headset will fade to black.
/// </example>
[AddComponentMenu("VRTK/Scripts/Presence/VRTK_HeadsetCollision")]
public class VRTK_HeadsetCollision : MonoBehaviour
{
    [Tooltip("If this is checked then the headset collision will ignore colliders set to `Is Trigger = true`.")]
    public bool ignoreTriggerColliders = false;
    [Tooltip("The radius of the auto generated sphere collider for detecting collisions on the headset.")]
    public float colliderRadius = 0.1f;
    [Tooltip("A specified VRTK_PolicyList to use to determine whether any objects will be acted upon by the Headset Collision.")]
    public VRTK_PolicyList targetListPolicy;

    /// <summary>
    /// Emitted when the user's headset collides with another game object.
    /// </summary>
    public event HeadsetCollisionEventHandler HeadsetCollisionDetect;
    /// <summary>
    /// Emitted when the user's headset stops colliding with a game object.
    /// </summary>
    public event HeadsetCollisionEventHandler HeadsetCollisionEnded;

    /// <summary>
    /// Determines if the headset is currently colliding with another object.
    /// </summary>
    [HideInInspector]
    public bool headsetColliding = false;
    /// <summary>
    /// Stores the collider of what the headset is colliding with.
    /// </summary>
    [HideInInspector]
    public Collider collidingWith = null;

    protected Transform headset;
    protected VRTK_HeadsetCollider headsetColliderScript;
    protected GameObject headsetColliderContainer;
    protected bool generateCollider = false;
    protected bool generateRigidbody = false;

    public virtual void OnHeadsetCollisionDetect(HeadsetCollisionEventArgs e)
    {
        if (HeadsetCollisionDetect != null)
        {
            HeadsetCollisionDetect(this, e);
        }
    }

    public virtual void OnHeadsetCollisionEnded(HeadsetCollisionEventArgs e)
    {
        if (HeadsetCollisionEnded != null)
        {
            HeadsetCollisionEnded(this, e);
        }
    }

    /// <summary>
    /// The IsColliding method is used to determine if the headset is currently colliding with a valid game object and returns true if it is and false if it is not colliding with anything or an invalid game object.
    /// </summary>
    /// <returns>Returns `true` if the headset is currently colliding with a valid game object.</returns>
    public virtual bool IsColliding()
    {
        return headsetColliding;
    }

    /// <summary>
    /// The GetHeadsetColliderContainer method returns the auto generated GameObject that contains the headset collider.
    /// </summary>
    /// <returns>The auto generated headset collider GameObject.</returns>
    public virtual GameObject GetHeadsetColliderContainer()
    {
        return headsetColliderContainer;
    }

    protected virtual void Awake()
    {
        VRTK_SDKManager.AttemptAddBehaviourToToggleOnLoadedSetupChange(this);
    }

    protected virtual void OnEnable()
    {
        headset = VRTK_DeviceFinder.HeadsetTransform();
        if (headset != null)
        {
            headsetColliding = false;
            SetupHeadset();
            VRTK_PlayerObject.SetPlayerObject(headsetColliderContainer.gameObject, VRTK_PlayerObject.ObjectTypes.Headset);
        }
    }

    protected virtual void OnDisable()
    {
        if (headset != null && headsetColliderScript != null)
        {
            headsetColliderScript.EndCollision(collidingWith);
            TearDownHeadset();
        }
    }

    protected virtual void OnDestroy()
    {
        VRTK_SDKManager.AttemptRemoveBehaviourToToggleOnLoadedSetupChange(this);
    }

    protected virtual void Update()
    {
        if (headsetColliderContainer != null && headsetColliderContainer.transform.parent != headset)
        {
            headsetColliderContainer.transform.SetParent(headset);
            headsetColliderContainer.transform.localPosition = Vector3.zero;
            headsetColliderContainer.transform.localRotation = headset.localRotation;
        }
    }

    protected virtual void CreateHeadsetColliderContainer()
    {
        if (headsetColliderContainer == null)
        {
            headsetColliderContainer = new GameObject(VRTK_SharedMethods.GenerateVRTKObjectName(true, "HeadsetColliderContainer"));
            headsetColliderContainer.transform.position = Vector3.zero;
            headsetColliderContainer.transform.localRotation = headset.localRotation;
            headsetColliderContainer.transform.localScale = Vector3.one;
            headsetColliderContainer.layer = LayerMask.NameToLayer("Ignore Raycast");
        }
    }

    protected virtual void SetupHeadset()
    {
        Rigidbody headsetRigidbody = headset.GetComponentInChildren<Rigidbody>();
        if (headsetRigidbody == null)
        {
            CreateHeadsetColliderContainer();
            headsetRigidbody = headsetColliderContainer.AddComponent<Rigidbody>();
            headsetRigidbody.constraints = RigidbodyConstraints.FreezeAll;
            generateRigidbody = true;
        }
        headsetRigidbody.isKinematic = true;
        headsetRigidbody.useGravity = false;

        Collider headsetCollider = headset.GetComponentInChildren<Collider>();
        if (headsetCollider == null)
        {
            CreateHeadsetColliderContainer();
            SphereCollider newCollider = headsetColliderContainer.gameObject.AddComponent<SphereCollider>();
            newCollider.radius = colliderRadius;
            headsetCollider = newCollider;
            generateCollider = true;
        }
        headsetCollider.isTrigger = true;

        if (headsetColliderScript == null)
        {
            GameObject attachTo = (headsetColliderContainer ? headsetColliderContainer : headset.gameObject);
            headsetColliderScript = attachTo.AddComponent<VRTK_HeadsetCollider>();
            headsetColliderScript.SetParent(gameObject);
            headsetColliderScript.SetIgnoreTarget(targetListPolicy);
        }
    }

    protected virtual void TearDownHeadset()
    {
        if (generateCollider)
        {
            Destroy(headset.gameObject.GetComponent<BoxCollider>());
        }
        if (generateRigidbody)
        {
            Destroy(headset.gameObject.GetComponent<Rigidbody>());
        }
        if (headsetColliderScript != null)
        {
            Destroy(headsetColliderScript);
        }
        if (headsetColliderContainer != null)
        {
            Destroy(headsetColliderContainer);
        }
    }
}

public class VRTK_HeadsetCollider : MonoBehaviour
{
    protected VRTK_HeadsetCollision parent;
    protected VRTK_PolicyList targetListPolicy;

    public virtual void SetParent(GameObject setParent)
    {
        parent = setParent.GetComponent<VRTK_HeadsetCollision>();
    }

    public virtual void SetIgnoreTarget(VRTK_PolicyList list = null)
    {
        targetListPolicy = list;
    }

    public virtual void EndCollision(Collider collider)
    {
        if (collider == null || !VRTK_PlayerObject.IsPlayerObject(collider.gameObject))
        {
            parent.headsetColliding = false;
            parent.collidingWith = null;
            parent.OnHeadsetCollisionEnded(SetHeadsetCollisionEvent(collider, transform));
        }
    }

    protected virtual void OnTriggerStay(Collider collider)
    {
        if (parent.ignoreTriggerColliders && collider != null && collider.isTrigger)
        {
            return;
        }

        if (enabled && !VRTK_PlayerObject.IsPlayerObject(collider.gameObject) && ValidTarget(collider.transform))
        {
            parent.headsetColliding = true;
            parent.collidingWith = collider;
            parent.OnHeadsetCollisionDetect(SetHeadsetCollisionEvent(collider, transform));
        }
    }

    protected virtual void OnTriggerExit(Collider collider)
    {
        if (parent.ignoreTriggerColliders && collider != null && collider.isTrigger)
        {
            return;
        }

        EndCollision(collider);
    }

    protected virtual void Update()
    {
        if (parent.headsetColliding && (parent.collidingWith == null || !parent.collidingWith.gameObject.activeInHierarchy))
        {
            EndCollision(parent.collidingWith);
        }
    }

    protected virtual HeadsetCollisionEventArgs SetHeadsetCollisionEvent(Collider collider, Transform currentTransform)
    {
        HeadsetCollisionEventArgs e;
        e.collider = collider;
        e.currentTransform = currentTransform;
        return e;
    }

    protected virtual bool ValidTarget(Transform target)
    {
        return (target != null && !(VRTK_PolicyList.Check(target.gameObject, targetListPolicy)));
    }
}

}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 211,884评论 6 492
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 90,347评论 3 385
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 157,435评论 0 348
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 56,509评论 1 284
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 65,611评论 6 386
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 49,837评论 1 290
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,987评论 3 408
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 37,730评论 0 267
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,194评论 1 303
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,525评论 2 327
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,664评论 1 340
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,334评论 4 330
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,944评论 3 313
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,764评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,997评论 1 266
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 46,389评论 2 360
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 43,554评论 2 349

推荐阅读更多精彩内容