Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 13 Next capture
2021 2022 2023
1 capture
13 Jun 22 - 13 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
1
Question by JoshMBeyer · Dec 07, 2012 at 09:33 AM · howrangedetectto

How to detect range?

Hi, I was wondering how can I detect range? What I am trying to do is when my player character comes within range of the door on a house, then do something.

My Player: //Is made off the first person controller dragged into the hierarchy.

Player (FirstPersonController dragged onto a "Player" named prefab.)

>graphics (Part of the FirstPerson Controll) >CameraHead (Empty GameObject) I have a script attached to my player to make the camera follow the player by having the same transform position as of "CameraHead". This is my "CameraScript" using UnityEngine;
using System.Collections;


/// /// This script is attached to the player and it /// causes the camera to continuously follow the /// CameraHead. ///




public class CameraScript : MonoBehaviour {


//Variables Start_


private Camera myCamera;


private Transform cameraHeadTransform;


//Variables End
___




// Use this for initialization
void Start ()
{
//A quick reference of the CameraHead's transform.
myCamera = Camera.main;


cameraHeadTransform = transform.FindChild("CameraHead");
}


// Update is called once per frame
void Update ()
{
//Make the camera follow the player's cameraHeadTransform.


myCamera.transform.position = cameraHeadTransform.position;


myCamera.transform.rotation = cameraHeadTransform.rotation;
}
}
Now what I want is to detect if my player is within range of the door of the house (the door has it's own script attached. using UnityEngine; using System.Collections;
/// /// This script is attached to the front door on the House. /// /// This script creates the ability to enter the House by when in /// range, a message appears "Press "O" to enter.", and if /// clicked load the InsideHouse level. ///
public class EnterHouseScript : MonoBehaviour {
//If within range the PlayerRange script will set this //boolean to true. private bool withInRange = false;
// Use this for initialization void Start () {
}
// Update is called once per frame void Update () { if(withInRange == true) { //Just a dummy function to test if I am in range print("You are within range"); } } }
What do I need to add, what script should I add it too, and what gameobject should I attach it too?
Comment
Add comment · Show 1
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image Ben-Stoneman ♦♦ · Dec 07, 2012 at 02:02 PM 0
Share

You will want to create a Raycast from the player to the object (door) http://docs.unity3d.com/Documentation/ScriptReference/RaycastHit-distance.html

2 Replies

· Add your reply
  • Sort: 
avatar image
5
Best Answer

Answer by Klakwa · Dec 07, 2012 at 07:03 PM

You can do that in several ways (as always).

If you want to track player by the door you can simply reference the player's transform.position and then compare it with the position of the door by using Vector3.Distance(). And then check if the distance is within the range or not.

 Vector3 doorPosition;
 Vector3 myPosition;
 
 int range = 10;
 
 if(Vector3.Distance(myPosition, doorPosition) < range)
 {
    //Do something
 }

You can also use Raycasting to cast rays from the player and see what they hit and what's the length of the ray. Using the Physics.Raycast() and then checking out the RaycastHit.distance or RaycastHit.collider.transform.position and compare it with the Player's position.

But I would probably use a collider as a trigger to simply trigger the event on when character goes near it. It simply eliminates the reason to look for the event to happen on each frame and it's easy to change and manipulate if you are using it for only one event.

So then you do it like that:

 OnTriggerStay(Collider objectWeCollideWith) // if you want the event to be called each frame the player is within the range
   {
      if(objectWeCollideWith.tag == "Player")
   {
      // Do something
   }
 }

If you want to activate more objects at once you can try the other way around. Have player to use Physics.OverlapSphere(playerPosition,range) to check out what colliders he's colliding with within certain range and then you can walk the list of them and perform some action. Like that:

 void CheckNearObjects()
 {
 Collider[] objects = Physics.OverlapSphere(transform.position, range);
 
 foreach(Collider object in objects)
 {
     if(object.tag == "Door")
     {
         object.DoSomething();
     }
 }
 }

Hope that helps.

Comment
Add comment · Show 2 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image JoshMBeyer · Dec 08, 2012 at 02:05 AM 0
Share

Thanks, that was very helpful

avatar image Klakwa · Dec 08, 2012 at 10:54 AM 0
Share

If you are using the collider as trigger you can also do it in another way not using OnTriggerStay() method, but ins$$anonymous$$d you can turn an event on while object enters the trigger using OnTriggerEnter() and then turn the event off using OnTriggerExit().

avatar image
1

Answer by zyzyx · Dec 07, 2012 at 03:09 PM

What Ben Stoneman said, or just check the Distance between player and door. You may want to cache the door object/s somewhere so you do not have to search it every time you want to check. Or let the door/s have a reference to the player transform.

Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

12 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

Multiple Cars not working 1 Answer

How to detect range of multiple gameobjects? 1 Answer

Need help finding a tutorial, pdf, or some sort of Documentation 0 Answers

How do i add textures without them stretching? 1 Answer

how to create scenes inside building in unity 2 Answers


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges