Allow player to pick up item only if they are in a certain radius.
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.
Are you having any problems with your code? If so, what are they?
wait if the game is 2d why are you using a 3d distance function
You don't need to use this
, transform.position
is the position of the transform that the script is attached to.