Picking up item if player is within a certain radius of the item.
I think I'm on the right track here, but I'm not entirely sure how to get it to work. In the game, the player will be able to interact with items in the world, but only if they are close enough to it. I'm trying to do this by taking the position of the player and the position of the item they are trying to pick up. I'm doing this by having a method in the Interactable class that will return true if the player can pick it up.
Here's my code for it so far:
using UnityEngine;
public class Interactable : MonoBehaviour
{
public float radius = 1;
GameObject player;
private void Start()
{
player = GameObject.FindWithTag("Player");
}
void Update()
{
if (Input.GetKeyDown("e"))
{
isCloseEnough(player);
}
}
void OnDrawGizmosSelected()
{
Gizmos.color = Color.red;
Gizmos.DrawWireSphere(transform.position, radius);
}
public bool isCloseEnough(GameObject player)
{
if (Vector3.Distance(player.transform.position, this.transform.position) < radius)
{
Debug.Log("Yeah, you're close enough to pick this up.");
return true;
}
else
{
return false;
}
}
}
Note: I'm using the "this" keyword because I want the script to refer to the GameObject that this script is a component of. Like, if there's a button in the world that the player can press, I want the script to refer to that button, but I don't know how to do that exactly. Also the game is in 2d. I don't know if that's of significance here, but if it is, now you know.
Thanks for any help.
Your answer
Follow this Question
Related Questions
Allow player to pick up item only if they are in a certain radius. 0 Answers
RPG Picking up items with polymorphism - probably quick :) 1 Answer
Using an object transform to trigger a series of blendShapes 1 Answer
controlling objects with a character controlled by a nav mesh agent 0 Answers
Need help with Socket Interactor 0 Answers