【问题标题】:XNA: How to change texture reference midgame?XNA:如何在游戏中更改纹理参考?
【发布时间】:2013-01-21 22:13:41
【问题描述】:

我目前正在 XNA 中制作游戏。到目前为止我进展顺利,但我不知道如何在运行游戏时更改精灵的纹理。这就是一个例子。当角色静止时,这是一个形象,然后当他走路时,这是一个不同的形象。我将如何做到这一点?

【问题讨论】:

    标签: c# xna


    【解决方案1】:

    运行检查并将实例的 Texture2D texture 设置为预加载库中的其他纹理。

    我通常将我的内容文件夹中的所有纹理加载到字典中并像这样使用:

    var StringTextureDic = new Dictionary<string, Texture2D>();
    
    // code that loads all textures into the dictionary, file names being keys
    
    // whenever I need to assign some texture, I do this:
    if (!playerIsMoving)
        Player.texture = StringTextureDic["player standing"];
    
    if (playerIsMoving)
        Player.texture = StringTextureDic["player moving"];
    

    【讨论】:

    • 感谢您的回复,但是每当我使用您的这个字典方法时,游戏就会崩溃并显示“字典中不存在给定的键。”
    【解决方案2】:

    实际上,在游戏中期更改玩家纹理是个坏主意。在这种情况下,我更喜欢使用纹理表。

    Rectangle frame;
    int curFrame;
    int frameWidth;  
    int frameHeight;
    int runAnimationLength;
    
    Update()
    {
    //Handle your "animation code"
    if(playerIsMoving)
         curFrame++; //Running
         if(curFrame == runAnimationLength)
              curFrame =0;
    else 
    curFrame = 0; //Standing still
    }
    Draw(SpriteBatch spriteBatch)
    {
    frame = new Rectangle(curFrame*frameWidth,curFrame*frameHeight,frameWidth,frameHeight);
    spriteBatch.Draw(
    texture,
    position,
    **frame**, 
    color, 
    rotation, 
    origin, 
    SpriteEffects.None,
    1);
    }
    

    【讨论】:

    • 为什么在游戏中期改变玩家纹理是个坏主意?
    • 嗯,它使用了更多的资源并且不太灵活。具有多个文件的情况: 1. 将纹理分配给变量 2. 绘制此纹理 3. 卸载旧纹理 4. 加载新纹理 5. 分配新纹理 6. 绘制新纹理 使用纹理表的情况: 1. 将纹理分配给变量 2 . 绘制(同时绘制和循环帧)
    • 你假设某处有纹理卸载,但实际上没有,就像使用精灵条一样——你永远不会卸载很少使用的帧。使用精灵条而不是单个纹理时可能会提高性能,但这超出了这个问题的范围。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-16
    • 1970-01-01
    相关资源
    最近更新 更多