繁体   English   中英

如何从另一个类加载精灵并在输入XNA上对其进行更改

[英]How to load sprite from another class and change it on input XNA

我只是在学习XNA,还有一些基本问题。

  1. 假设我有Car类,想加载/绘制精灵。 我该怎么办? Xna为此创建了方法,但它们在Game类中。

  2. 在使用自定义类处理我的精灵后,我的类具有3个状态,具体取决于状态。 我希望它绘制不同的精灵。 我想将它们全部加载到Texture2d数组中。

正如您所说,这些方法在Game类中,除非您从根本上改变事物的工作方式,否则您必须习惯于这一事实。

但是,一旦您从DrawableGameComponent继承(如果您希望它们绘制/更新,所有游戏对象都应该这样做),您将看到所有对象无论如何都需要将Game类传递给构造函数,因为他们的基类。 然后可以从那里使用它来加载纹理:

public class Car : DrawableGameComponent
{
    private Texture2D texture;

    public Car(Game game) : base(game)
    {
        texture = game.Content.Load<Texture2D>("mytexture");
    }
}

或保留对它的引用并在以后加载。 这也意味着在Game1.cs某处您有类似

Car car = new Car(this);

或者,如果您要从其他文件加载该文件,则该文件需要知道您的Game类才能创建您的汽车。

要绘制精灵,只需使用

public override void Draw(GameTime gameTime)

DrawableGameComponent方法。


如果您想减轻痛苦,您仍然可以创建一个静态类来保存您的Game类(可能还有您的SpriteBatch ,因为这将非常有用):

public static class GameHolder
{
    public static Game Game { get; set; }
}

因此,您的游戏组件可以这样创建:

public class Car : DrawableGameComponent
{
    private Texture2D texture;

    public Car() : base(GameHolder.Game)
    {
        texture = GameHolder.Game.Content.Load<Texture2D>("mytexture");
    }
}

并且不要忘记从Game1类中获取Game值:

public class Game1 : Game
{
    public Game1()
    {
        graphics = new GraphicsDeviceManager(this);
        GameHolder.Game = this;
    }
}

要处理状态,实际上可以将它们全部加载到一个数组中并打印其中之一。 要从Draw方法中删除逻辑,您还可以使用另一个Texture2D来保存要渲染的当前精灵。

public class Car : DrawableGameComponent
{
    private List<Texture2D> states;
    private Texture2D currentState;
    private SpriteBatch spriteBatch;

    public Car(Game game, SpriteBatch sb) : base(GameHolder.Game)
    {
        states.Add(game.Content.Load<Texture2D>("state1"));
        states.Add(game.Content.Load<Texture2D>("state2"));
        states.Add(game.Content.Load<Texture2D>("state3"));
        currentState = states[0];
        spriteBatch = sb;
    }
    public override void Update(GameTime gameTime)
    {
        if (someCondition)
        {
            currentState = states[0];
        }
        else if (someOtherCondition)
        {
            currentState = states[1];
        }
        else if (moreConditions)
        {
            currentState = states[2];
        }

        base.Update(gameTime);
    }

    public override void Draw(GameTime gameTime)
    {
        spriteBatch.Draw(currentState, new Vector2(0,0), Color.White);

        base.Draw(gameTime);
    }
}

如您所见,Draw方法实际上并不关心您要处理的多个状态。


如果您需要详细的教程,那么Platformer Starter Kit确实很棒。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM