如何检测一个游戏对象何时进入另一个游戏对象的区域? [英] How can I detect when a gameobject enters the area of another gameobject?

查看:45
本文介绍了如何检测一个游戏对象何时进入另一个游戏对象的区域?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个脚本,可以使游戏对象移动到某个高度,例如200. 在地形上,我还有另一个游戏对象.我希望当他开始进入另一个游戏对象区域时移动的第一个游戏对象做某事.

I have a script that make a gameobject to move in some height for example at 200. On a terrain i have another gameobject. I want that when the first gameobject that move when he start entering the other gameobject area do something.

void OnTriggerEnter(Collider other)
    {
       if (other.gameObject.name == "Base")
      {

      } 
    }

但是这不起作用,因为在转换和基础"之间没有物理碰撞.转换高度为200.

But this is not working since there is no physical collide between the transform and the "Base". transform is at height 200.

我也尝试使用Raycast Hit. 在脚本的顶部,我添加了:

I also tried to use Raycast hit. In the top of the script i added:

Collider col;

然后在更新中

    Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
    RaycastHit hit;
    if (col.Raycast(ray, out hit, 100.0F))
    {
        Debug.Log("Hit !");
    }

但是,这种转换又是悬而未决的. 这个想法是,一旦转换开始进入Base区域,就要做一些事情.

But again the transform is in the air. The idea is to do something once the transform start entering the Base area.

推荐答案

实现该目标的简单方法:

Simple way to achieve that:

  • 使基础的子游戏对象只有一个Box Collider组件(isTrigger设置为true)
  • 在y轴上扩展此游戏对象的碰撞器(将其视为支柱),如下所示:

  • Make a child game object of the base, with only a Box Collider component (isTrigger set to true)
  • Extend the collider of this game object on the y axis (think of it as a pillar), like this:

使用以下代码将脚本附加到移动的游戏对象上:

Attach a script to your moving game object, with this code:

using UnityEngine;

public class CheckBaseCollider : MonoBehaviour {
    public GameObject baseCollider;

    private void OnTriggerEnter(Collider other) {
        if (other.gameObject == baseCollider) {
            Debug.Log("Entered");
        }
    }
}

你很好.

这篇关于如何检测一个游戏对象何时进入另一个游戏对象的区域?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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