【Unity】Xiao Baixiang---pick up simple items in your hand

    As a brief introduction, I am a beginner in Unity. I have been studying the problem of how to pick up items in my hands for nearly three days, but I still don’t understand how to achieve it. What appears on the Internet is either deleting the item or picking up and dragging the item with the mouse.

    Let’s take a look at the implementation first

    Aim at the item to be picked up (note that it must be a rigidbody component, add a colider component, and have a sphere collision domain). When the camera/character enters the collision domain, you can press a specific key to trigger the pickup.

The picked object is the bandage in the picture

 

show collision domain

 

Inspector page (you must add sphere box and rigidbody to pick up!)

   After creating the object, create an empty object under the main camera main-camara or your character, and move the empty object to a position you think is appropriate (this is the "hand", or the position where the object is to be moved)

As shown in the picture:

After creating the empty object GameObject, create a C# script

I named it tack script here

code show as below

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class tack : MonoBehaviour
{

    private bool canCollect = false;
    //判断是否进入碰撞域
    private GameObject target;
    //对象target
    [SerializeField] Transform ItemSlot;
    //“手”
    void Update()
    {
        //一旦检测到按下f且符合能拾取条件,就拾取
        if (Input.GetKeyDown(KeyCode.F))
        {
            if (canCollect)
            {
                target.transform.SetParent(ItemSlot);             //设立父对象
                target.transform.localEulerAngles = Vector3.zero; //设置相对于父对象的角度为0
                target.transform.localPosition = Vector3.zero;    //设置相对于父对象的位置为0
            }
        }
    }

    private void OnTriggerEnter(Collider other)    //碰撞域进入判断
    {
        // 判断名称,设置可拾取状态,并将目前碰撞到的对象引用给予target
        if (other.gameObject.tag == "item")
        {
            canCollect = true;
            target = other.gameObject;
        }
    }

    private void OnTriggerExit(Collider other)    //碰撞域退出判断
    {
        // 退出碰撞箱范围,禁用拾取,解除target的引用
        if (other.gameObject.tag == "Item")
        {
            canCollect = false;
            target = null;
        }
    }
}

After finishing writing the script code, mount it on the main camera or character.

Then mount the previously created empty object GameObject to this Item Slot.

 

Then run the code

 

 Finish

-----===================================================================-----

  This is my first time writing a blog, and I haven’t been self-studying Unity for a long time, so some of the professional names may not be very accurate. I welcome your criticisms, corrections, exchanges and learning! ! !

Guess you like

Origin blog.csdn.net/hhhnzd/article/details/130070824