【问题标题】:XNA game items drag and drop — how to implement object exchange?XNA游戏物品拖放——如何实现对象交换?
【发布时间】:2012-09-15 18:01:34
【问题描述】:

我正在制作一个库存系统,但我被困在应该通过简单的拖放将项目从一个单元格移动到另一个单元格的部分。

有一个 Item[,] Inventory 数组保存项目,object fromCell, toCell 应该保存对单元格的引用,以便在释放鼠标按钮时进行操作,但是当我尝试这样做时:

object temp = toCell;
toCell = fromCell;
fromCell = temp;

...游戏只是交换对象引用而不是实际对象。我该如何完成这项工作?

UPD:感谢 Bartosz,我明白了这一点。事实证明,您可以安全地使用对对象数组的引用,并使用保存的您希望交换的对象的索引来更改 it

代码可以是这样的:

object fromArray, toArray;
int fromX, fromY, toX, toY;

// this is where game things happen

void SwapMethod()
{
    object temp = ((object[,])toArray)[toX, toY];
    ((object[,])toArray)[toX, toY] = ((object[,])fromArray)[fromX, fromY];
    ((object[,])fromArray)[fromX, fromY] = temp;
}

【问题讨论】:

    标签: c# swap


    【解决方案1】:

    这个怎么样?

    internal static void Swap<T>(ref T one, ref T two)
    {
        T temp = two;
        two = one;
        one = temp;
    }
    

    你所有的交换都变成了这个。

    Swap(Inventory[fromCell], Inventory[toCell]);
    

    此外,您可以为数组添加扩展名(如果更舒适)。

    public static void Swap(this Array a, int indexOne, int indexTwo)
    {
        if (a == null)
            throw new NullReferenceException(...);
    
        if (indexOne < 0 | indexOne >= a.Length)
            throw new ArgumentOutOfRangeException(...);
    
        if (indexTwo < 0 | indexTwo >= a.Length)
            throw new ArgumentOutOfRangeException(...);
    
        Swap(a[indexOne], a[indexTwo]);
    }
    

    像这样使用它:

    Inventory.Swap(fromCell, toCell);
    

    【讨论】:

    • 问题是,您能否传递对通过索引器方法获得的对象的引用?
    • 我的错,当然可以用于数组,但不能用于自定义索引器 (this[index])。
    • 第一个根本不起作用,因为我没有通过一种方法获得fromto 单元格,而且单次使用几秒钟似乎有点过大。不过还是谢谢。
    【解决方案2】:

    为什么不使用Inventory 数组的索引:int fromCell, toCell

    var temp = Inventory[toCell];
    Inventory[toCell] = fromCell;
    Inventory[fromCell] = temp;
    

    您将库存建模为 2D 插槽数组,因此使用索引访问它似乎相当安全。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-04-02
      • 2012-04-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-09
      • 2011-08-16
      相关资源
      最近更新 更多