我目前有一个关于方法中局部变量的问题。 该方法是在屏幕底部生成一排方形精灵,当前代码如下所示:

 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)

===============>>#1 票数: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();
        }
    }
}

===============>>#2 票数:0 已采纳

根据您发布的代码,无法分辨出什么损坏了。 问题很可能是如何创建Wall 我敢打赌, positionModifier.X实际上对墙的x位置没有任何作用,或者墙的x位置的起始值为0,并且在方法调用中将positionModifier乘以它时,它仍为0。

  ask by CraigGame translate from so

未解决问题?本站智能推荐: