简体   繁体   中英

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:

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. 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 .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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