Calculate distance between player and object
Hello, I made a script to pick items up. I'm wondering if anyone can help me add some sort pf thing so that the script can detect how far away the player is. Basically so you can't pick the items up anywhere, and you have to be close to them. Thanks in advanced. #pragma strict
var item : GameObject;
function Start () { gameObject.transform.localRotation = Quaternion.Euler(0,0,0); }
function Update () { if(Input.GetKey(KeyCode.E)) { Drop(); } }
function Drop() { //Destroy the object that has this script attached Destroy(gameObject); }
Answer by phaninder15 · Nov 21, 2017 at 10:08 AM
You can calculate distance from object using Vector3.Distance(object.position,player.position);
float minDist=2;
float dist = Vector3.Distance(other.position, transform.position);
if(dist < minDist)
{
pickup();
}
Hello, thank you for the reply! how would I add this into my script? I'm new to scripting.
When you want to pick up, for example if you want to pickup when player press Button E
void Update()
{
if(Input.Get$$anonymous$$eyDown($$anonymous$$eyCode.E))
{
float dist = Vector3.Dist(object.positon,player.position);
if(dist<$$anonymous$$Dist)
{
pickup();
}
}
}
I've added it into the script($$anonymous$$ay be incorrectly placed) and I keep getting two errors saying to add semicolons but when I do the error doesn't go. Here's the script so far #pragma strict
var item : GameObject;
function Start () { gameObject.transform.localRotation = Quaternion.Euler(0,0,0); }
void Update() { if(Input.Get$$anonymous$$eyDown($$anonymous$$eyCode.E)); { float $$anonymous$$Dist=2; float dist = Vector3.Distance(other.position, transform.position); if(dist < $$anonymous$$Dist) { pickup(); }
Drop();
}
}
function Drop() { //Destroy the object that has this script attached Destroy(gameObject); }