Handling Score When Collision of XNA
-
14-07-2021 - |
Question
I just want to handle score when the Land collide on a ship i created in 2D game in XNA game studio.. Life(Score) is settled to 100 variable called Life in GameLife class...
i want to reduce life by 2 points when two objects collided...
But the problem is when the ship collided on a Land the the the life is instantly going to minus values till ship object keep away from land object... please give me a help...
the Code is provided here
`private void HandleLandCollition(List<LandTile> landtiles)
{
foreach (LandTile landtile in landtiles)
{
rectangle1 = new Rectangle((int)landtile.position.X - landtile.texture.Width / 2,
(int)landtile.position.Y - landtile.texture.Height / 2,
landtile.texture.Width, landtile.texture.Height);//land object
rectangle2 = new Rectangle((int)position.X - texture.Width / 2,
(int)position.Y - texture.Height / 2,
texture.Width, texture.Height);//rectangle2 is defined to ship object
if (rectangle1.Intersects(rectangle2))
{
shiplife.Life = shiplife.Life - 2;
}
}
}
La solution
Your problem is probably that you call this method every frame. Usually XNA calls Update() 60 times per second, so if your ship touches the landtile for a second, it loses 2*60 = 120 healthpoints, which results in the minus values you're seeing.
My solution would be this:
protected override void Update(GameTime gameTime)
{
float elapsedTime = (float) gameTime.ElapsedTime.TotalSeconds;
HandleCollision(landtiles, elapsedTime);
}
float landDamagePerSecond = 2;
private void HandleLandCollision(List<LandTile> landtiles, float elapsedTime)
{
shipRectangle= new Rectangle((int)position.X - texture.Width / 2,
(int)position.Y - texture.Height / 2,
texture.Width, texture.Height);//rectangle2 is defined to ship object
foreach (LandTile landtile in landtiles)
{
landRectangle= new Rectangle(
(int)landtile.position.X - landtile.texture.Width / 2,
(int)landtile.position.Y - landtile.texture.Height / 2,
landtile.texture.Width, landtile.texture.Height);//land object
if (landRectangle.Intersects(shipRectangle))
{
shiplife.Life -= landDamagePerSecond * elapsedTime;
}
}
}
elapsedTime is the time since the last frame was called, by multiplicating this with the damage the landtile deals to the ship per second will result that the ship loses 2 healthpoints per second when it touches a landtile ;)