0

这是我正在进行的一个项目的代码,其中一个敌人在屏幕底部来回移动。

class enemy1
{
    Texture2D texture;
    public Vector2 position;
    bool isAlive = false;
    Random rand;
    int whichSide;
    public enemy1(Texture2D texture, Vector2 position)
    {
        this.texture = texture;
        this.position = position;
    }

    public void Update()
    {
        if (isAlive)
        {
            if (whichSide == 1)
            {
                position.X += 4;

                if (position.X > 1000 + texture.Width)
                    isAlive = false;
            }
            if (whichSide == 2)
            {
                position.X -= 4;

                if (position.X < 0)
                    isAlive = false;
            }
        }
        else
        {
            rand = new Random();
            whichSide = rand.Next(1, 3);
            SetInStartPosition();
        }
    }

    private void SetInStartPosition()
    {
        isAlive = true;
        if (whichSide == 1)
            position = new Vector2(0 - texture.Width, 563 - texture.Height);
        if (whichSide == 2)
            position = new Vector2(1000 + texture.Width, 563 - texture.Height);
    }

    public void Draw(SpriteBatch spriteBatch)
    {
        spriteBatch.Draw(texture, position, Color.White);
    }
}

现在我希望有几个敌人来回走动,但他们从不同的位置开始,所以看起来屏幕底部有几个敌人来回走动。我已经设法在屏幕上绘制了一些其他敌人,但它们的行为不像第一个敌人。它们只是屏幕上的图片,不会在任何地方移动。所以现在我只有移动的英雄和屏幕底部的一个敌人,以及坐在屏幕顶部的其他 5 个敌人什么都不做。我如何随时轻松地从具有相同行为的类中添加新的精灵,同时又不创建十亿个变量来存储它们?

4

1 回答 1

0

Generally it's a good idea to have similar logic contained within the proper class, so if all Sprites where to do the same thing, then all you would need to do is put your movement code inside a public method and then call that method inside Update().

So, if your Sprite class looks something like this:

public class Sprite
{
    private Vector2 Position; 
    public Sprite(Texture2D texture, Vector2 position)
    {
       Position = position; 
    }

    //then just add this
    public void MoveSprite(int amount)
    {
        position.X += amount; 
    }
}

Now, the object name "Sprite" is pretty generic, you will more than likely have many "Sprites" in your game.

So you're going to want to follow good OOP practices and maybe name this specific sprite something different and then have it derive from this class we're looking at right now. (But i'm not going to make design decisions for you)

This was a vague question, but that's my best shot at an answer for you.

于 2013-01-13T06:00:38.050 回答