- Home /
How to perform some code if you are close to an object
Hey guys, I am trying to make a script that when you are close to an object, it prints some GUI to the screen.
But what I am having trouble with is figuring a way to check if you are in a certain range of an object..... I know you can do this somehow with raycasting, but I'm not sure how to do it.....
Any help would be greatly appreciated!!!!
-Grady
Answer by crazyKnight · Jun 28, 2011 at 05:09 AM
the most easy way to approach this will be to make a cube around the object(the one on which you need to print a gui)make it a trigger the size of the cube will depend upon the range you want .
then apply the following code on the cube
function OnTriggerEnter(info : Collider)
{
if(info.gameObject.tag == "your object tag")
{
// do your required work here....
}
}
yeah, but how would i execute the code when i'm a certain distance away from an object?????
Suppose you want to execute the code when you are 100 units away from the object. In that case make the cube 200 units wide/tall/whatever. Or use a sphere with a radius of 100 units.
Or, if you don't like that approach, you have two vectors, the position of the object in the scene and the position of your player. Vector3.Distance() will tell you the distance between these two positions, and then you can do your code if it's less than some value in units.
Answer by Sirex · Jun 28, 2011 at 12:01 PM
This is a modified library function that i have written for these things. Call it from an update function in some script and it should work. Hope this is around what you were looking for!
def FindObjectWithTag(newPosition as Vector3, tag as string, objectRadius as double):
ColliderList = Physics.OverlapSphere(newPosition, objectRadius)
resultObject as duck = null
for listObject in ColliderList:
if listObject.tag == tag:
return true
//resultObject = listObject
//return resultObject.gameObject
return false
I'd recommend looking at SphereCastAll() and testing against returned coliders for their tags. You should get better performance from this I think.
so it would send out a sphere that when it collides with anything, then you can get it to run some code.. I also had a raycasting script which i was using but it works, but i'm not sure if anyone would be able to improve it... here it is:
var rayCastLength = 100000;
function Update () {
var hit : RaycastHit;
if(Physics.Raycast(transform.position, transform.forward, hit, rayCastLength))
{
if(hit.collider.gameObject == "GA$$anonymous$$EOBJECTTAG")
{
Application.LoadLevel(0);
}
}
}
I hope you can read it with out it being colour coded.... thanks
-Grady
Your answer
Follow this Question
Related Questions
Raycasts and new Gui buttons 0 Answers
Detect if player is in range? 2 Answers
IDragHandler goes through buttons 0 Answers
How to get a game object to lerp as a triggered effect? 3 Answers