I am using Tiled (http://www.mapeditor.org) to generate my maps and TiledSharp (https://github.com/marshallward/TiledSharp) to load and draw my map.
So far so good. Map is drawn correcty (in correct layers) and hero movement is correct.
What I do not get. How to check collision between player and objects?
In my Update() I have something like
if (ks.IsKeyDown(Keys.W))
{
playerMovement += new Vector2(0, -2);
curAnimation = "Walk_North";
}
...
if (playerMovement.Length() != 0)
player.MoveBy(playerMovement);
Checking the .tmx file for the map, there is my group with object I can collide with:
<objectgroup name="Collision">
<properties>
<property name="collision" type="bool" value="true"/>
</properties>
<object id="1" x="1089" y="1118" width="62" height="65"/>
<object id="2" x="801" y="1026" width="61" height="60"/>
</objectgroup>
What I am now looking for is something like
If(tileAt(player.Position + playerMovement).Properties.Collision)
playerMovement = Vector2.Zero();
I think, everything is I need is there and I am just missing a simple step to compare players' position with the target position and its property :(
Any suggestions or examples would be appreciated. (Maybe just need to calculate it by myself in a simple method...)
Figured it out, actually quite easy:
First, in my class managing my map I set up an List with my collisionobjects.
foreach(var o in curMap.ObjectGroups["Collision"].Objects)
collisionObjects.Add(new Rectangle((int)o.X, (int)o.Y, (int)o.Width, (int)o.Height));
In my UpdateGame() method I call a simple helper-method from my map-class checking for intersection:
public bool IsCollisionTile(Rectangle player)
{
foreach (Rectangle rect in collisionObjects)
if (rect.Intersects(player))
return true;
return false;
}
Finished.
More effort writing this posting than the actual implementation ^^