How can i possibly detect if the player is near at the object . Without the help of 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
. 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;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.