- Home /
Javascript Distance Check Not Working
I'm working on a script which means that if a player presses the 'e' key when close to another player, they will attack. Although I can see in the inspector that the variable 'distance1' is working and changing as the characters move, I don't get any of my Debug.Log statements and pressing the e key does nothing. I'm guessing this means that the statement 'if(distance1 < 2)' is never fulfilled. Any ideas why this could be? Thanks.
var distance1: float;
function Update () {
var manager = GameObject.Find("NetworkManager");
var script = manager.GetComponent(NetworkManagerScript);
var Player1 = script.Player1;
distance1= Vector3.Distance(gameObject.transform.position, Player1.transform.position);
if(distance1 < 2){
Debug.Log("Close");
if(Input.GetKeyDown("e")){
Debug.Log("Dead");
Destroy(Player1);
}
}
}
Here is a better version of yours:
var distance1: float;
var Player1:GameObject;
function Start() {
var manager = GameObject.Find("Network$$anonymous$$anager");
var script = manager.GetComponent(Network$$anonymous$$anagerScript);
Player1 = script.Player1;
}
function Update(){
distance1= Vector3.Distance(gameObject.transform.position,Player1.transform.position);
if(distance1 < 3){
Debug.Log("Close");
if(Input.Get$$anonymous$$eyDown("e")){
Debug.Log("Dead");
Destroy(Player1);
}
}
}
Also, try with a greater value than 2. See your player may be be already between 0.5 and 1 wide and same for the other player meaning that they would have to be touching each other (don't laugh will you) for the statement to work.
Also the "distance1" variable should be declared inside Update, unless you're using it in another function.
Answer by Despot · Apr 02, 2013 at 09:46 AM
Thanks for the responses, but for future reference, the issue was that for some reason it wasn't taking the distance from a network instantiated player. I fixed it by adding all the if statements into an 'if(networkView.isMine)' statement.
Your answer
Follow this Question
Related Questions
Spawn along local axis. 3 Answers
Finding Distances With Vector3 1 Answer
GUI Counter Based on Animation or RaycastHit 0 Answers
What is causing my AI script to interpret wrong data? 1 Answer
distance script not working!!! 1 Answer