简体   繁体   English

XNA游戏项目拖放-如何实现对象交换?

[英]XNA game items drag and drop — how to implement object exchange?

I'm making an inventory system and I'm stuck at the part where the items should be moved from cell to cell by simple drag'n'dropping. 我正在建立一个库存系统,并且停留在应该通过简单的拖放将项目从一个单元移动到另一个单元的部分。

There is an Item[,] Inventory array which holds the items, object fromCell, toCell which should hold the references to cells to operate with when mouse button is released, but when I try doing this: 有一个Item[,] Inventory数组,其中包含项目, object fromCell, toCell ,这些object fromCell, toCell应包含对单元格的引用,以便在释放鼠标按钮时进行操作,但是当我尝试这样做时:

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

...the game is only swapping object references and not the actual objects. ...游戏只是交换对象引用,而不交换实际对象。 How do I make this work? 我该如何工作?

UPD: Thanks to Bartosz I figured this out. UPD:感谢Bartosz,我弄清楚了这一点。 Turns out you can safely use a reference to array of objects and change it with saved indices of objects you wish to swap. 事实证明,您可以安全地使用对对象数组的引用,并使用要交换的对象的已保存索引对其进行更改。

Code can be like this: 代码可以像这样:

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;
}

How about this? 这个怎么样?

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

And all your swapping becomes this. 您所有的交换都变成了这个。

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

Also, you can add the extension for the arrays (if more confortable). 另外,您可以为数组添加扩展名(如果更方便的话)。

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]);
}

To use it like so: 像这样使用它:

Inventory.Swap(fromCell, toCell);

Why not using indexes to your Inventory array: int fromCell, toCell . 为什么不对Inventory数组使用索引: int fromCell, toCell

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

You're modeling inventory as 2D array of slots, so it seems fairly safe to use indexes to access it. 您将库存建模为插槽的2D数组,因此使用索引访问它似乎相当安全。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM