- Home /
Need help with Tricky problem with Distance calculation
Hey!
i set up a 3d object that when clicked up loads up a screen with item that users can purcase stuff.
And is that I want it to load only when the user gets a certain distance to the object.
some the code ended up being weird, and in unity the player has to first get close to the object then click on it before the screen pops up.
which isn't what I wanted. I want the ui to only show when the player is close enough and the player has clicked on the object. Any ideas as to what the issue is?
using System.Collections;
using System.Collections.Generic;
using UnityEngine.UI;
using UnityEngine;
public class Vending : MonoBehaviour
{
//VARIABLES
public Shop foodShop;
public GameObject player;
public GameObject machine;
public float Distance;
public UnityEngine.AI.NavMeshAgent playerAgentV;
void Start()
{
playerAgentV = GetComponent<UnityEngine.AI.NavMeshAgent>();
}
void Update()
{
if (Input.GetMouseButtonDown(0) && !UnityEngine.EventSystems.EventSystem.current.IsPointerOverGameObject())
{
GetVendingInteraction();
}
}
void GetVendingInteraction()
{
Ray interactionRay = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit interactionInfo;
if (Physics.Raycast(interactionRay, out interactionInfo, Mathf.Infinity))
{
//I THINK THIS IS WHERE THE ISSUE IS
//I've tried changing the order and the parameters of the if statement but the problem persists
machine = interactionInfo.collider.gameObject;
Distance = Vector3.Distance(player.transform.position, machine.transform.position);
if (machine.tag == "Vending Machine" && Distance <= 4)
{
Debug.Log("OPEN VENDING MACHINE UI");
foodShop.shopContainerVisibility.SetActive(true); //turn shop UI visibility on
}
}
}
}
honestly if there is a different way to tackle this feature, i'm open to suggestions.
What is it doing right now? Is it just not showing up?
So right now:
You click the 3d object
The player moves to said object
You click the 3d object again
Then the UI pops up (becomes visible)
I want it to
Click on the object
The user gets close to it (distance is recorded) and if distance is less than 4f: open the UI
Could use some clarification of what's going on and what you're trying to achieve because
some the code ended up being weird, and in unity the player has to first get close to the object >then click on it before the screen pops up.
which isn't what I wanted. I want the ui to only show when the player is close enough and the >player has clicked on the object. Any ideas as to what the issue is?
From what you say it looks like it's doing exactly what it should?
Tubestorm EgoAnt · (just now) So right now:
You click the 3d object
The player moves to said object
You click the 3d object again
Then the UI pops up (becomes visible)
I want it to
Click on the object
The player gets close to it (distance is recorded) and if distance is less than 4f: open the UI