0

I have searched for three days and didn't find a solution, Here is the code:

if (keyboardState.IsKeyDown(Keys.Right))
{
    for (int i = GlobalClass.BlocksPositions.Count - 1; i > 0; i--)
    {
        if (new Rectangle((int)GlobalClass.BlocksPositions[i].X, (int)GlobalClass.BlocksPositions[i].Y, bT.Width, bT.Height).Intersects(new Rectangle((int)Position.X, (int)Position.Y, Texture.Width, Texture.Height)))
        {

            c = 0;
        }
        else
        {
            c = 1;
        }
    }

    if (c == 1)
    {
        Position.X += Speed;
    }

}

Each Block position equals a block that I can create by clicking on the screen, the new block position is then put in the List. Basically I have a list of blocks Coordinates in my BlockPosition List. Then I pass the condition for each blockposition, the Condition Create A rectangle for each BlockPosition and one for the Player... if there's a collision, the player won't move in that direction. When I try the code, My character will Collide only with the first element of the List and not the others, if I delete the first element it will then collide with the next one but not the others. All the variables are FINE I know it because I tried to replace this code by something like this:

if (keyboardState.IsKeyDown(Keys.Right))
{
    for (int i = GlobalClass.BlocksPositions.Count - 1; i > 0; i--)
    {
        if (new Rectangle((int)GlobalClass.BlocksPositions[i].X, (int)GlobalClass.BlocksPositions[i].Y, bT.Width, bT.Height).Intersects(new Rectangle((int)Position.X, (int)Position.Y, Texture.Width, Texture.Height)))
        {
            GlobalClass.BlocksPositions.RemoveAt[i];

        }
    }
}

Same thing but here if it collides I delete the Element of the List, it's the same condition but when I try it it will detect all of the elements and delete the ones that I touch. I tried the foreach function and I get the same Results. What's wrong? I already do a lot of things with does variables So I'm sure the problem don't come from their values but with what I do with them. Help please! (:

4

3 回答 3

2

如果if计算结果为true,您什么也不做,而且您似乎也不需要该c变量。怎么样...

if (keyboardState.IsKeyDown(Keys.Right))
{
    foreach( var pos in GlobalClass.BlocksPositions.Reverse() )
    {
        var rect = new Rectangle((int)pos.X, (int)pos.Y, bT.Width, bT.Height);
        var rectToTest = new Rectangle((int)Position.X, (int)Position.Y, Texture.Width, Texture.Height);
        if (!rect.IntersectsWith(rectToTest))
            Position.X += Speed;
        else
            break;
    }
}

如果您确实需要c某种状态管理,则可以将其重新添加。

于 2011-08-04T00:37:27.140 回答
0

即使您找到了交叉点,您的循环也会继续。您需要在 if 语句的 true 子句中中断。

于 2011-08-04T00:41:28.253 回答
0

为了便于阅读,请考虑以下内容:

if (GlobalClass.BlocksPositions.All(x => !DoesIntersect(Position, x))
     Position.X += speed;

不仅目的更容易推断,而且您所犯的特定错误也不会出现。

于 2011-08-04T01:00:45.170 回答