Collision Detection

Depending on how closely you want to integrate with Xen, you can handle collisions at the Xen2D level with each sprite and/or extents, or at the XenGameBase level with event handlers.

Collision with Extents

With extents provided from a Xen sprite or created in your code, you can check for intersections. It works like this:
            if( _spriteRed.RenderingExtent.Intersects( _spriteBlue.RenderingExtent ) )
            {
                Vector2 collisionPoint = _spriteRed.RenderingExtent.FindClosestPoint( _spriteBlue.RenderingExtent.ActualCenter );
                // ... code ...
            }

GameBase Collision Events

When using GameBase, collisions are more closely integrated into the game class. You can add child elements to the game's built-in MainScene layer and override the OnMainSceneCollisionHandler() or to your own custom Layers.
First, we need to create an Element2D class to add to the layer:
    class CollidableElement : ComplexElement2D<CollidableElement>
    {
        public static CollidableElement Acquire( Vector2 position, Texture2D texture )
        {
            var instance = _pool.Acquire();
            instance.Sprite = StaticSprite.Acquire( texture );
            instance.RenderingExtent.Anchor = position;
            return instance;
        }
        public StaticSprite Sprite;
        protected override void ResetDirectState()
        {
            //Note: always set Visual Component, then base.ResetDirectState()
            VisualComponents.Add( Sprite );
            base.ResetDirectState();

            CollisionClass = CollisionClasses.Default;
        }
    }
Then we can add them to the MainScene like this:
    public class GameMain : GameBase
    {
        protected override void LoadContent()
        {
            MainScene.Children.Add( CollidableElement.Acquire( new Vector2( 200, 200 ), Content.Load<Texture2D>( "Textures/Red" ) ) );
            MainScene.Children.Add( CollidableElement.Acquire( new Vector2( 400, 200 ), Content.Load<Texture2D>( "Textures/Blue" ) ) );
            base.LoadContent();
        }
        // ... code ...
        protected override void OnMainSceneCollisionHandler( CollisionEventArgs collisionEvent )
        {
            collisionEvent.A.Release();
            collisionEvent.B.Release();
        }
    }

Last edited Feb 7, 2011 at 12:03 AM by twohalf, version 2

Comments

No comments yet.