C# Dictionary Question

Started by
2 comments, last by TheTroll 11 years, 11 months ago
So I need a way to be able to relate my game actors with the physics body that represents them. To do that I use the following code:


private Dictionary<ActorId, int> bodyIdLookup; //matches a game actor ID to corrosponding physics body ID


However the problem is that I want to be able to do two things: 1) look up the game actor Id given the physics body Id 2) look up the physics body Id given the game actor Id. As I see it, the dictionary class only allows you to look up a value given it's corresponding key and not the other way around. Is this true? Can I implement this functionality without having another dictionary with the physics Id as a key and ActorId as a value?
J.W.
Advertisement

However the problem is that I want to be able to do two things: 1) look up the game actor Id given the physics body Id 2) look up the physics body Id given the game actor Id.


This is usually a sign that you're doing something wrong. If you have a 1 to 1 relationship where both sides will want to know about the other... you might as well just make them one object.


As I see it, the dictionary class only allows you to look up a value given it's corresponding key and not the other way around. Is this true?
[/quote]

Essentially. To do the reverse lookup, you'll need to iterate through the dictionary, which is not speedy. It also doesn't guarantee a single key for the value you're searching for.


Can I implement this functionality without having another dictionary with the physics Id as a key and ActorId as a value?
[/quote]

Sure, though having the second dictionary is the most straight-forward without simply putting references in the object itself.

[quote name='jdub' timestamp='1336858117' post='4939634']
However the problem is that I want to be able to do two things: 1) look up the game actor Id given the physics body Id 2) look up the physics body Id given the game actor Id.


This is usually a sign that you're doing something wrong. If you have a 1 to 1 relationship where both sides will want to know about the other... you might as well just make them one object.
[/quote]
Or use composition. Most physics engines let you store an arbitrary pointer/object reference with a physics object. Then your object would store a reference to the physics object. Thus establishing the 1-1 relationship.

In time the project grows, the ignorance of its devs it shows, with many a convoluted function, it plunges into deep compunction, the price of failure is high, Washu's mirth is nigh.

No sure why you would want a Dictionary to do this. The "easy" way would be to put a reference in the objects to each other so that if you are using one you can quickly get to the other one. Now, this does tightly couple your code between the two, but in this case I don't see that as a bad thing.

This topic is closed to new replies.

Advertisement