Unity游戏鼠标拾取、放下物体

关于拾取、放下游戏物体,要先在游戏物体上加入标签tag,这里我统一将可以拾取的物体标志为pickedObject。然后对游戏添加rigidbody、collider组件,只有这三步都做到才可以拾取物体。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class pick : MonoBehaviour
{
    private float smooth=10;
    private float depth=0.5f;
    Transform currentObject;
    Vector3 mouse3DPosition;
    //public Text lifeText;
    //手机UI界面
    public GameObject smartphoneUI;
    void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            if (currentObject == null)
            {
                Ray rays = Camera.main.ScreenPointToRay(Input.mousePosition);
                Debug.DrawRay(rays.origin, rays.direction * 100, Color.yellow);
                RaycastHit hit;
                if (Physics.Raycast(rays, out hit))
                {//将创建的射线投射出去并将反馈信息存储到hit中
                    if (hit.collider.gameObject.tag == "pickedObject")
                    {
                        
                        
                        currentObject = hit.transform;
                        currentObject.gameObject.SetActive(false);
                    }     //获取被射线碰到的对象transform变量
                }

            }
            else
            {
                
                currentObject.gameObject.SetActive(true);
                Vector3 mp = Input.mousePosition;
                mp.z = depth;
                mouse3DPosition = Camera.main.ScreenToWorldPoint(mp);
                currentObject.position = Vector3.Lerp(currentObject.position, mouse3DPosition, smooth );
                currentObject = null;
            }
        }

    }
}

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值