使物体检测到射线投射不再击中它 [英] Making an object detect that raycast not hitting it anymore

查看:159
本文介绍了使物体检测到射线投射不再击中它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用SendMessage通知被Raycast击中的对象:

I use SendMessage to inform the Object that is was hit by a Raycast:

     using UnityEngine;

 public class Raycaster : MonoBehaviour {
     void Update() {
         RaycastHit hit;
         if (Physics.Raycast(transform.position, transform.forward, out hit))
          if(hit.transform.tag == "MyGameObject"){
            hit.transform.SendMessage ("HitByRay");
            }  
     }
 }

对象具有如下脚本:

using UnityEngine;

 public class ObjectHit : MonoBehaviour {
     void HitByRay () {
         Debug.Log ("I was hit by a Ray");
     }
 }

在每帧中显示该打印消息我被雷击中". 现在,我需要通知光线投射的游戏物体不再击中它.

And that print message "I was hit by Ray" in every frame. Now i need to inform that Game Object that raycast not hitting it anymore.

推荐答案

@Eddge是正确的,存储对热门游戏对象的引用是正确的方法.检查以下代码:

@Eddge is right, storing a reference to the hit gameobject is the way to go. Check the following code :

public class Raycaster : MonoBehaviour
 {
     private bool hitting = false;
     private GameObject hitObject;

     void Update()
     {
         RaycastHit hit;
         if (Physics.Raycast(transform.position, transform.forward, out hit))
         {
            if(hit.transform.tag == "MyGameObject")
            {
                GameObject go = hit.transform.gameobject ;

                // If no registred hitobject => Entering
                if( hitObject == null )
                {
                    go.SendMessage ("OnHitEnter"); 
                }
                // If hit object is the same as the registered one => Stay
                else if( hitObject.GetInstanceID() == go.GetInstanceID() )
                {
                    hitObject.SendMessage( "OnHitStay" );
                }
                // If new object hit => Exit last + Enter new
                else
                {
                    hitObject.SendMessage( "OnHitExit" );
                    go.SendMessage ("OnHitEnter");
                }

                hitting = true ;
                hitObject = go ;
            } 
         }
         // No object hit => Exit last one
         else if( hitting )
         {
            hitObject.SendMessage( "OnHitExit" );
            hitting = false ;
            hitObject = null ;
         }
     }
 }

这篇关于使物体检测到射线投射不再击中它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆