AiTest2/EnemySprite.cs
Download
aitest2.zip
(14.13 KB | 07 July 2010 )
Sample project for implementing collision detection in the sprites of the Boulder Dash (Boulderdash) arcade game.
Donate
If this site or its services have saved you time, please consider a donation to help with running costs and timely updates.
Contents of aitest2.zip/AiTest2/EnemySprite.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace AiTest
{
abstract class EnemySprite : Sprite
{
#region Protected Constructors
protected EnemySprite(Direction preferredDirection, Direction fallbackDirection)
{
this.PreferredDirection = preferredDirection;
this.FallbackDirection = fallbackDirection;
}
#endregion Protected Constructors
#region Public Overridden Methods
public override CollisionAction GetCollisionAction(Sprite collidedWith)
{
CollisionAction result;
if (collidedWith is PlayerSprite)
result = CollisionAction.Explode; // Kill player
else
result = CollisionAction.None; // Do nothing
return result;
}
public override void Move()
{
Tile tile;
Sprite collision;
collision = null;
// first see if we can move in our preferred direction
tile = this.GetAdjacentTile(this.GetNewDirection(this.PreferredDirection));
if (!this.Map.IsScenery(tile) && !this.IsCollision(tile.Location, out collision))
{
// we can move here, update our position and also set our new direction
this.Location = tile.Location;
this.Direction = this.GetNewDirection(this.PreferredDirection);
}
else
{
// can't move in our preferred direction, so lets try the direction the sprite is facing
tile = this.GetAdjacentTile(this.Direction);
if (!this.Map.IsScenery(tile) && !this.IsCollision(tile.Location, out collision))
{
// we can move here, update our position, but not the direction
this.Location = tile.Location;
}
else
{
// can't move forwards either, so finally lets just turn in our fallback direction
this.Direction = this.GetNewDirection(this.FallbackDirection);
}
}
// if we collided with a sprite, lets execute the action
if (collision != null && this.GetCollisionAction(collision)== CollisionAction.Explode)
{
// kill both this sprite and the one we collided with
this.Map.Sprites.Remove(collision);
this.Map.Sprites.Remove(this);
}
}
#endregion Public Overridden Methods
#region Protected Properties
protected Direction FallbackDirection { get; set; }
protected Direction PreferredDirection { get; set; }
#endregion Protected Properties
}
}
