- Home /
Question by
AnJoBo · Aug 30, 2018 at 01:55 PM ·
uinavmeshagentplayer movementnavigationinteraction
How do I close in the distance between the player and object to pick up?
I mostly followed along with the tutorial here to get a chunk of my mobility for my PlayerController script.
The problem I'm running into is that when the player clicks the "Pick Up" button I have that pops up (being positioned when player clicks on an object with the tag of "Pickup") it just picks up (sets active to false) without closing in the distance.
I tried making it similar to the shootDistance variable made in the tutorial linked above that makes the player shoot when the enemy is close enough, but it isn't working...
Here's my code:
using UnityEngine;
using UnityEngine.AI;
using UnityEngine.EventSystems;
using UnityEngine.UI;
public class PlayerController : MonoBehaviour
{
public GameObject matUI;
public GameObject inventoryManager;
public GameObject selectionOptions;
public GameObject dialoguePanel;
public Text dialogueText;
public bool isMoving;
public float touchableDistance = 2f;
private NavMeshAgent navMeshAgent;
private Vector3 destination;
private bool hoverActive;
private string hoverName;
private float hoverPointX;
private float hoverPointY;
private GameObject selection;
private bool inRange;
void Awake()
{
navMeshAgent = GetComponentInChildren<NavMeshAgent>();
isMoving = false;
inRange = false;
selectionOptions.SetActive(false);
dialoguePanel.SetActive(false);
}
void Update()
{
Ray mouseRay = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit mouseHit;
if (Physics.Raycast(mouseRay, out mouseHit, 100))
{
// Checks for click
if (Input.GetButtonDown("Fire1"))
{
destination = mouseHit.point;
// If player clicked or taps a UI element **** Doesn't work right on mobile ****
if (EventSystem.current.IsPointerOverGameObject() ||
EventSystem.current.currentSelectedGameObject != null)
{
return;
}
// If player clicks or taps a pickup
else if (mouseHit.collider.CompareTag("Pickup"))
{
selection = mouseHit.collider.gameObject;
selectionOptions.transform.position = new Vector3(Input.mousePosition.x, Input.mousePosition.y, 0);
selectionOptions.SetActive(true);
}
// Just move to selected area
else
{
selectionOptions.SetActive(false);
dialoguePanel.SetActive(false);
MoveTo(destination);
}
}
}
}
private void MoveTo(Vector3 destination)
{
isMoving = true;
navMeshAgent.isStopped = false;
navMeshAgent.destination = destination;
}
public void Pickup()
{
MoveTo(destination);
if (navMeshAgent.remainingDistance >= touchableDistance)
{
navMeshAgent.isStopped = false;
isMoving = true;
}
if (navMeshAgent.remainingDistance <= touchableDistance)
{
navMeshAgent.isStopped = true;
isMoving = false;
selection.SetActive(false);
}
selectionOptions.SetActive(false);
}
public void Inspect()
{
dialogueText.text = "Looks useful!";
dialoguePanel.SetActive(true);
}
}
Comment