im making an RPG, and all is going quite ok, made a level system, gold etc, my problem now is i want to make quests, and the NPC's must only be 2-3 meters away to be clicked at,
i know i shall use Vector3, and on mouse click, but i dont know how to do it, what comamnds to use, i checked out various sites, but this whole scripting thing is still very new to me, so if some kind sould could guide me though it, i would be really glad! make an example or something and what to put on where :) and i should be able to manage the rest ^^
thanks alot in advance!
Any object with a Collider component will fire events like OnMouseOver() which can be found in the MonoBehaviour class reference.
As for the distance checking, there are a few ways to do this. The less expensive way is to have a spherical collider that is set to a trigger and a radius of 1-1.5 (2-3 meters in diameter in Unity measurements). From there you can attach a behaviour script that looks sort of like this:
Another way to do it using the vector3 method would be to use Vector3.Distance()
[Edit] here is the Vector3 method that Mike suggested below, in greater detail:
// this script should be attached to whatever the player will be interacting with. please insure that the game object this script is a component of also has a collider otherwise OnMouseDown won't fire.
//called when the user presses down on the left mouse button over the attached game object's collider.
public var dist:int = 2;
function OnMouseDown()
{
/*
in order for this to just work, please chance "Player" below to whatever the root GameObject
which your Player is inside of is named.
*/
var _playerPosition : Vector3 = GameObject.Find("Player").transform.position;
/*
here we check if the distance between our "Player" and the game object this script is attached to
is less then or equal to our defined distance variable <dist>
*/
if(Vector3.Distance(_playerPosition,transform.position) <= dist)
{
print("I should print something if you are in range and click on me.");
//insert all of your code to reveal interaction GUI here.
}}
Expanding on equalsequals' suggestion about Vector3.Distance:
function OnMouseDown()
{
if(Vector3.Distance(yourPlayerTransform.position, transform.position) > 2) return;
//do your interaction stuff below this line
}
where yourPlayerTransform is the transform component on your player