- Home /
Checking the distance between an instantiated object and an existing object
Hi there! In my game, if a person is struck by lightning, then they die. The lightning spawns wherever the user clicks, and I don't know how to check to see if the lighting bolt(which is instantiated) spawns near enough the person. The lightning bolt spawns at the x and z point of the click, and the y point has 100 added to it.
Here is my script to far (I know I misspelt the lightning variable):
var lightingBolt : GameObject;
var hit : RaycastHit;
var person : GameObject;
var distance = Vector3.Distance(lightingBolt.transform.position, person.transform.position);
function Update () {
if (Input.GetButtonDown ("Fire1")) {
var ray = Camera.main.ScreenPointToRay (Input.mousePosition);
if (Physics.Raycast (ray, hit)) {
hit.point.y = hit.point.y + 100;
Instantiate (lightingBolt, hit.point, transform.rotation);
if(distance)
{}
}
}
}
Answer by oatsbarley · Jan 26, 2014 at 10:19 AM
Instantiate()
returns the instantiated object, so you can get its transform and then use that to find the distance:
var bolt = (GameObject)Instantiate(lightingBolt,
hit.point, transform.rotation);
float distance = Vector3.Distance(bolt.transform.position,
person.transform.position);
if (distance < 10f) {
// do your thing
}
Obviously change 10f
to whatever distance you want to check for, but this should work otherwise.
Sorry for my late response, but would that code take into account that the lightning spawns y+100 above the person?
You can adjust the lightning position when you do the distance calculation like so:
float distance = Vector3.Distance(
bolt.transform.position + Vector3.down * 100,
person.transform.position);
Again, sorry for responding much later after you replied. Your script executes the if statement no matter how far away I am to the person, and it is only supposed to be 1f
var lightingBolt : GameObject;
var hit : RaycastHit;
var person : GameObject;
var distance : float = Vector3.Distance(lightingBolt.transform.position + Vector3.down * 100, person.transform.position);
function Update () {
if (Input.GetButtonDown ("Fire1")) {
var ray = Camera.main.ScreenPointToRay (Input.mousePosition);
if (Physics.Raycast (ray, hit)) {
hit.point.y = hit.point.y + 100;
Instantiate (lightingBolt, hit.point, transform.rotation);
if(distance > 1f)
{
person.SetActive(false);
}
}
}
}
Your answer
Follow this Question
Related Questions
Spawn along local axis. 3 Answers
How to get access to child's objects of instantiated prefab on JS? 1 Answer
Instantiate as a child at position 2 Answers
distance to variable object 1 Answer