Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
YnQuadTree in action with 50 sprites. This gist demonstrate you how it is simple to use a QuadTree structure in a game using Yna Engine. More information on the project page http://yna.codeplex.com
public class TestYnQuadTree
{
private List<YnSprite> sprites;
private YnSprite heroSprite;
private YnQuadTree quadTree;
public TestGame()
{
// Init some Sprites
sprites = new List<YnSprite>();
for (int i = 0; i < 50; i++)
{
// Create and init 50 Sprites
YnSprite sprite = new YnSprite("SpriteAsset");
sprite.Position = new Vector2(Math.Random() * YnG.Width, Math.Random() * YnG.Height);
// Add the sprite to the scene
Add(sprite);
// Add the sprite to the collection of collidable objects
sprites.Add(sprite);
}
// Init the player
heroSprite = new Sprite("HeroAsset");
heroSprite.Position = new Vector2(Math.Random() * YnG.Width, Math.Random() * YnG.Height);
Add(heroSprite);
// Init the QuadTree
quadTree = new YnQuadTree(0, new Rectangle(0, 0, YnG.Width, YnG.Height));
quadTree.MaxObjectsPerNode = 10;
}
public override void Update(GameTime gameTime)
{
base.Update(gameTime);
// Update the quadtree structure
quadTree.Begin(spriteToCollide.ToArray());
// Move your hero, do what you want ;)
someUpdateLogic();
// mSprite is the tested Sprite (you can use an array of ICollider2, so you can have a different object on mSprite parameter)
// lSprite is the candidate that can be tested
quadTree.Test(heroSprite, (mSprite, lSprite) =>
{
// If collide the heroSprite take its last position
if (heroSprite.Rectangle.Intersects(lSprite.Rectangle))
heroSprite.Position = heroSprite.LastPosition;
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.