因此,每次发生碰撞时(恒星对象与行星对象之间),我将计数器迭代1,但最终会迭代大量。
public override void Update(GameTime gameTime)
{
int count = 0;
if (star.getBound().Intersects(planet.getBound()))
{
count += 1;
}
}
问题是因为它是更新,我认为它会不断迭代,所以我尝试将其放在draw函数中,但它仍然增加了很多。
星状对象有问题吗?因为在达到某个y位置后,在我的星级课程中,我只是将其替换。
//inside update function of star object
pos.Y += speed;
Random random = new Random();
if (pos.Y > 500)
{
pos = new Vector2(1 * random.Next(10, 700), 1 * random.Next(0, 200));
}
我想知道这不是更新问题,还是后者,我该怎么办,因为当我尝试将其绘制时,它的行为几乎相同。
您的问题有点令人困惑,但我会尽力而为。
1)每帧都调用Update和Draw。这可能就是为什么您每次看到它都被称为(迭代)的原因。2)切勿将逻辑代码放入Draw方法中。此方法应保持尽可能短,仅用于渲染3)每次调用Update时,Count都设置为0。您可能希望使其成为班级的成员。
我们提供的代码示例很少,可以为您提供更多帮助。请给我们更多信息,我们可以为您提供更好的答案。
将Update()
视为While循环,一直运行直到游戏停止。
while (true /*game is running*/) {
int count = 0;
if (star.getBound().Intersects(planet.getBound())) {
count += 1;
}
}
现在您将开始在这里看到一些问题:
count
不断地重置为1。(只需删除该语句)为了解决后一个问题,您可以使用布尔值作为状态来确定恒星是否已经发生碰撞,然后确定要采取的措施,例如:
bool isColliding = false;
public override void Update(GameTime gameTime) {
if (!isColliding) {
// Was not colliding, just started colliding.
if (star.getBound().Intersects(planet.getBound())) {
count += 1;
isColliding = true;
}
} else {
// Was colliding, just stopped colliding.
if (!star.getBound().Intersects(planet.getBound())) {
isColliding = false;
}
}
}
仅当恒星和行星刚开始相互碰撞时,这允许代码添加分数。