How can I decrement lives on collision, using XNA with C#?

岁酱吖の 提交于 2019-12-24 09:33:30

问题


I have an assignment for my computer graphics class, were we have to alter a game code. The class itself is entirely about theory, so we pretty much have to figure out the code for ourselves and I've never programmed in C#, so sorry for any ignorance on my part.

Whenever my player sprite is hit by a box, I want the lives variable to decrement by 1. However, whenever it gets hit it just keeps going down. I understand why this is happening, but I don't know how to stop it.

This is the code that checks wether the two objects have collided.

if (b.BoundBox.Intersects(player.BoundSphere)){
    player.hit = true;
}

In the update function for the player I have:

if(hit){
    lives -= 1
}

How can I make it decrements only once, instead of constantly?


回答1:


This is happening because it will constantly be detecting that it is colliding, as long as part of one of the objects is inside the other it will say that it is colliding.

What you can do to work around this is when the objects collide, set a boolean value that says the objects have collided and start a timer for however many seconds. While the boolean value is set to true, when the objects collide it will not decrement the lives but if it is false it will decrement. Once the timer is up, set the value to false so they can keep colliding. This gives the object time to leave the 'innards' of the other object.

Edit:

This is a very simple fix and might not work in your situation (as i don't know the rules of the game). A more complete solution would be to push the objects apart just enough that they are no longer colliding or predict one update tick ahead where each object will be and prevent them from ever actually colliding.




回答2:


You don't need a timer for this problem, just declare another bool that keeps track if you've updated lives.

if (b.BoundBox.Intersects(player.BoundSphere) && !player.hit)
{
    player.hit = true;
    player.updated = false;
}

In your player's update:

if (hit && !updated)
{
    lives -= 1
    updated = true;
}

However, if you want to use a counter simply declare a:

TimeSpan timer = new TimeSpan(0, 0, x); //where x is how many seconds you need

and then in the Update method:

timer -= gameTime.ElapsedGameTime;
if (timer <= TimeSpan.Zero)
{
   // do what you want
}


来源:https://stackoverflow.com/questions/19509167/how-can-i-decrement-lives-on-collision-using-xna-with-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!