Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have an array which I'm using to store map data for a game I'm working on.

MyMapType[,,] map; 

The reason I'm using a fixed array instead of a Collection is because fixed arrays work very much faster.

Now my problem is, I'd like to have support for negative z levels in the game. So I'd like to be able to access a negative index.

If this is not possible, I thought of a pair of other solutions.

I was thinking as a possible solution to have ground-level as some arbitrary number (say 10), and anything less than 10 could be considered negative. But wouldn't this make the array 10 times larger for nothing if its not in use?

Another solution I considered was to 'roll my own' where you have a Dictionary of 2D arrays, with the Z level held in the List as the index. But this is a lot more work and I'm not sure if its slow or not.

So to summarise - any way of creating an array which supports a negative index? And if there's not - is there a clean way of 'emulating' such behaviour without sacrificing too much CPU time or RAM - noting that these are game maps which could end up large AND need to be accessed constantly.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
458 views
Welcome To Ask or Share your Answers For Others

1 Answer

replace your arrays with a class:

class MyArray {
    private MyMapType[] myArray = new myMapType[size]
    MyMapType this[index] {
       get{return myArray[index + offset];}
    }

}

you can set the size and the offset in the constructor or even change it at will.

Building on this example here is another version:

class MyArray {
    private MyMapType[] positives = new myMapType[size]
    private MyMapType[] negatives = new myMapType[size-1]
    MyMapType this[index] {
       get{return index >= 0 ? positives[index] : negateves[1-index];}
    }

}

It does not change the fact that you need to set the size for both of them. Honestly I like the first one better


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...