简易模拟背包效果

//效果脚本

using UnityEngine;
using System.Collections;

public class Scriptone : MonoBehaviour
{
    //2、场景中有一个方块,鼠标点击后方块跟随鼠标移动,当再次点击到圆柱时方块放到该圆柱的上方。(要求使用射线)
    // 用来做初始化
    void Start()
    {
    }
    // 每帧都会调用一次 
    Transform cube;
    void Update()
    {
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        //main: 主显示器 //:ScreenPointToRay :屏幕位置转射线 //mousePosition : 鼠标位置
        RaycastHit hit;//Raycast : 射线投射
        //处理点击事件
        if (Input.GetMouseButtonDown(0))
        {
            if (Physics.Raycast(ray, out hit))
            {
                if (hit.collider.CompareTag("Box")) // 如果射线射向了Tag为"BOX"的标签
                {
                    cube = hit.collider.transform;//它的位置等于鼠标射线的位置
                    cube.GetComponent<Collider>().enabled = false;//自身的碰撞器置为false
                }
                else if (hit.collider.CompareTag("Cylinder"))//如果射线射向了Tag为"Cylinder"的标签
                {
                    if (cube)
                    {
                        Vector3 point = hit.collider.transform.position;
                        point.y = 1.4f;//固定cube的y轴位置为1.4f;
                        cube.transform.position = point;//自身的位置置为鼠标射线指向标签为"Cylinder"的位置
                        cube.GetComponent<Collider>().enabled = true;//自身的碰撞器置为true;
                        cube = null;//cube置为null 不会在进入上一次的判断;
                    }
                }
            }
        }
        if (cube)
        {
            //更新射线的位置
            if (Physics.Raycast(ray, out hit))
            {
                Vector3 point = hit.point;
                point.y = 1.4f;//固定cube的y轴位置为1.4f;
                cube.position = point;
            }
        }
    }
}

简易模拟背包效果

//鼠标点击Cube 可拖动Cube 到其他圆柱上