Unity3D仿星露谷物语开发34之单击Drop项目

1、目标

当在道具栏中选中一个Item时,点击地面就可以实现Item的drop操作,每点击一次就drop一次,直到道具栏中Item数量不够。

这样的好处:避免每次Drop都从道具栏中拖拉Item,通过点击这种操作可以更加高效。

方法:通过EventHandler脚本创建Event,在Player脚本中处理点击并触发Event,在UIInvenrotySlot脚本中订阅Event进行处理。

2、优化EventHandler脚本

添加如下事件代码:

3、优化Player脚本

添加如下变量:

cs 复制代码
private GridCursor gridCursor;

添加Start方法:

cs 复制代码
private void Start()
{
    gridCursor = FindObjectOfType<GridCursor>();
}

在Update中添加如下代码:

其具体实现如下:

cs 复制代码
private void PlayerClickInput()
{
    if (Input.GetMouseButton(0))
    {
        if (gridCursor.CursorIsEnabled)
        {
            ProcessPlayerClickInput();
        }
    }
}

相关的代码实现如下:

cs 复制代码
 private void ProcessPlayerClickInput()
 {
     ResetMovement();

     // Get Selected item details
     ItemDetails itemDetails = InventoryManager.Instance.GetSelectedInventoryItemDetails(InventoryLocation.player);

     if(itemDetails != null)
     {
         switch (itemDetails.itemType)
         {
             case ItemType.Seed:
                 if (Input.GetMouseButtonDown(0))
                 {
                     ProcessPlayerClickInputSeed(itemDetails);
                 }
                 break;
             case ItemType.Commodity:
                 if (Input.GetMouseButtonDown(0))
                 {
                     ProcessPlayerClickInputCommodity(itemDetails);
                 }
                 break;
             case ItemType.none:
                 break;
             case ItemType.count:
                 break;

             default:
                 break;
         }
     }
 }

 private void ProcessPlayerClickInputSeed(ItemDetails itemDetails)
 {
     if(itemDetails.canBeDropped && gridCursor.CursorPositionIsValid)
     {
         EventHandler.CallDropSelectedItemEvent();
     }
 }

 private void ProcessPlayerClickInputCommodity(ItemDetails itemDetails)
 {
     if(itemDetails.canBeDropped && gridCursor.CursorPositionIsValid)
     {
         EventHandler.CallDropSelectedItemEvent();
     }
 }

4、优化UIInventorySlot脚本

在OnEnable方法中增加如下代码,订阅事件并进行处理。

5、运行程序

相关推荐
云边散步12 分钟前
godot2D游戏教程系列一(3)
游戏
垂葛酒肝汤12 分钟前
Unity第一个项目
unity·游戏引擎
向前V17 分钟前
Flutter for OpenHarmony数独游戏App实战:单元格交互与选中
flutter·游戏·交互
Sator118 分钟前
Unity的InputSystem常见问题和疑惑解答
java·unity·游戏引擎
Remember_99326 分钟前
【数据结构】初识 Java 集合框架:概念、价值与底层原理
java·c语言·开发语言·数据结构·c++·算法·游戏
郝学胜-神的一滴29 分钟前
QtOpenGL多线程渲染方案深度解析
c++·qt·unity·游戏引擎·godot·图形渲染·unreal engine
云边散步1 小时前
godot2D游戏教程系列一(4)
游戏
2501_944525761 小时前
Flutter for OpenHarmony数独游戏App实战:笔记功能
笔记·flutter·游戏
世人万千丶2 小时前
鸿蒙跨端框架 Flutter 学习 Day 4:网络交互——HTTP 请求基础与数据反序列化实战
网络·学习·flutter·ui·交互·harmonyos·鸿蒙
IMPYLH2 小时前
Lua 的 Table 模块
开发语言·笔记·后端·junit·游戏引擎·lua