简体   繁体   中英

How do I interact with objects?

My Query

I am just learning Unity and I haven't been able to find comprehensive guide on how to interact with objects in a top down game.

My Solution

I have used the following code to create a radius for an object, in which you are able to interact with the said object, however I have no idea how to put the plan in motion. I have seen people use PlayerController, but I am not sure I should use it with RigidBody. Here's my Interactable.cs:

using UnityEngine;

public class Interactable : MonoBehaviour
{
    public float radius = 1.0f;

    private void OnDrawGizmosSelected() {
        Gizmos.color = Color.yellow;
        Gizmos.DrawWireSphere(transform.position, radius);
    }
}

What I need help with

Could someone point me in the right direction on how to interact with an object when player is inside the radius, on an example of removing the object?

This code solves your problem. You must inject the player instance at the beginning of each Interactable object. Then it is enough to measure the distance through Vector.Distance. Definitely a shorter distance is in the range.

private GameObject player;
public float radius = 1.0f;
public void OnEnable() => player = GameObject.FindWithTag("Player");
public void Update()
{
    var distance = Vector3.Distance(player.transform.position, transform.position);
    if (distance <= radius)
    {
        Debug.Log("Player is range of: "+name);
    }
}

Also remember that you have specified the player tag.

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM