局部变量不变

时间:2014-04-20 00:06:11

标签: c# variables xna local

我目前在方法中有关于局部变量的问题。该方法是在屏幕底部产生一行方形精灵。代码目前如下:

 public void spawnFloor()
    {
        for (int x = 0; x < floorSize / texture.Width; x++)
        {
            if (walls.Count < floorSize / texture.Width)
            {
                positionModifier.X = texture.Width * x;
                position.Y = floorStart.Y;
                spawnWall();
            }
        }
    }

目前,当游戏分辨率为1280/720时,游戏会在屏幕右下角产生40个方格。 x的值在整个过程中显然为0。有任何想法吗?以下是该类的完整代码,以防它基于类:

    public WallManager(Texture2D texture, Vector2 floorStart, int screenLength)
    {
        this.texture = texture;
        this.floorStart = floorStart;
        floorSize = screenLength;
    }

    public void spawnWall()
    {
        Wall thisWall = new Wall(position*positionModifier, texture);
        walls.Add(thisWall);
    }

    public void spawnTest()
    {
        if (walls.Count == 0)
        {
            position = new Vector2(0, 698);
            spawnWall();
        }
    }

    public void spawnFloor()
    {
        for (int x = 0; x < floorSize / texture.Width; x++)
        {
            if (walls.Count < floorSize / texture.Width)
            {
                positionModifier.X = texture.Width * x;
                position.Y = floorStart.Y;
                spawnWall();
            }
        }
    }
    public void Draw(SpriteBatch spriteBatch)
    {
        foreach(Wall wall in walls)

        wall.Draw(spriteBatch);
    }
}

编辑:正如建议的那样,已经发布了墙类:

public Wall(Vector2 position, Texture2D texture)
    {
        wallPosition = position;
        wallTexture = texture;
    }

    public void Update(GameTime gameTime)
    {
        wallWidth = (int)Math.Round((double)wallTexture.Width);
        wallHeight = (int)Math.Round((double)wallTexture.Height);
        wallHitbox = new Rectangle((int)wallPosition.X, (int)wallPosition.Y, wallWidth, wallHeight);
    }

    public void Draw(SpriteBatch spriteBatch)
    {
        spriteBatch.Draw(wallTexture, wallPosition, wallColor);
    }

此外,positionModifier是wallManager类中的私有Vector2,启动时值为(1,1)

2 个答案:

答案 0 :(得分:0)

因为它在你的循环中正在进行Closures。将局部变量复制为x并将其存储为localVal(示例),然后在计算positionModifier时使用该变量

public void spawnFloor()
{
    for (int x = 0; x < floorSize / texture.Width; x++)
    {
        if (walls.Count < floorSize / texture.Width)
        {
            var localVal = x;
            positionModifier.X = texture.Width * localVal;
            position.Y = floorStart.Y;
            spawnWall();
        }
    }
}

答案 1 :(得分:0)

根据您发布的代码,无法判断是什么。问题很可能出在Wall的创建方式上。我敢打赌,positionModifier.X实际上并没有对墙的x位置做任何事情,或者墙x位置的起始值为0,并且当你在方法调用中将positionModifier与它相乘时,它仍然是0。