简体   繁体   English

如何检测玩家是否靠近 GameObject(C#)Unity5

[英]How to detect if player is near to a GameObject(C#)Unity5

How can i possibly detect if the player is near at the object .我怎么可能检测到玩家是否靠近物体。 Without the help of raycast.没有raycast的帮助。

Here is my code:这是我的代码:

[SerializedField]
Transform obj1;

public GameObject player;

void Update(){
    if(obj1.transform.position - player.position < 5) {
       audio.Play();
    }
}

This is what i like to obtain .这是我喜欢获得的。 How can i do it like that.我怎么能那样做。 Help please请帮忙

obj1.transform.position - player.position will return a Vector3 . obj1.transform.position - player.position将返回一个Vector3 You can use the magnitude of that vector as your distance:您可以使用该向量的大小作为距离:

if ((obj1.transform.position - player.position).magnitude < 5.0f)
    audio.Play();

As a bit of a performance tip, you can save an expensive square-root operation by instead using the magnitude squared:作为一个性能提示,您可以通过使用幅度平方来节省昂贵的平方根运算:

if ((obj1.transform.position - player.position).sqrMagnitude < 25.0f)
    audio.Play();

You can find whether an object is near another object with the following code:您可以使用以下代码确定一个对象是否靠近另一个对象:

float distance = Vector3.Distance(object1.transform.position, object2.transform.position);
float maxDistance = 10.0f;
bool isNear = distance <= maxDistance;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM