Search code examples
inheritanceobjectxnainstances

XNA - accessing vector2 across classes


I'm implementing a particle system- particle.cs which I need to access the vector2 of moving enemy location enemy.cs. I have multiple instance of the particle and also the enemy in < list> these are assigned in game1.cs.

My question is how do I access the enemies location from the < list> iset in game1 and make it availble in particle.cs. Borh particle.cs and enemy.cs are part of the Game namespae.

I have tried various approaches of assigning new instances of objects and assigning public set/get but no luck!

Thanks, Paul.

Adding further detials: I can add some real code when I'm back on my dev pc, but for now some further comments.

enemies.cs - is just a basic class with variables outlined - location, speed, size etc... although these are all defined in game1.cs with values.

In Game1.cs I have a list of all the enemies as well as another list of their positions.

I have a particle engine which is called in Game1.cs which in turn references particles.cs -> which is where I need to call the value of vector2 enemies location.

I tried calling the enemies location in particle.cs by establishin an instance of game1.cs but this is per particle and slows down game beyond running.

Which parts of the code shoudl I show?

Thanks


Solution

  • If your particle engine needs access to the list of enemies, then you can just pass the list as a parameter in the constructor of your particle engine.

    I assume you have something like this in your Game1:

    List<Enemy> enemies = new List<Enemy>();
    

    So change your particle engine constructor to receive a reference to a list of Enemy, and hold it in a private variable.

    class ParticleEngine
    {
        private List<Enemy> _enemies;
    
        public ParticleEngine(List<Enemy> enemies)
        {
            _enemies = enemies;
        }
    }
    

    and in Game1 when you construct your particle engine object, pass in the enemy list.

    ParticleEngine particleEngine = new ParticleEngine(enemies);
    

    Now in particle engine, you have access to the enemies through your member _enemies. And since it is a reference to the list, even if the list grows, shrinks, changes, you will still get access to its "current" members.

    EDIT: On re-reading, I see you want the enemy location in your particle.cs. This would imply that each and every particle needs to know the position of each and every enemy, and this is likely a bad design. A better solution would be to have your ParticleEngine (think ParticleManager) handle "correlating" the individual particles to the enemy position.