【问题标题】:(monogame) Multiple instances of sprite inherited object(monogame) sprite 继承对象的多个实例
【发布时间】:2016-03-19 04:07:57
【问题描述】:

我看到了与我所问的问题类似的问题,但它们并没有完全给出我正在寻找的答案。我希望我的精灵的 5 个实例显示在屏幕上并在不同的位置生成。出于某种原因,虽然不是 5 个实例,但精灵的每个“实例”都会增加确实出现在屏幕上的一个精灵的值。

Sprite.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;

namespace Lab05_2__Aaron_Benjamin_
{
class Sprite
{
    Texture2D mSpriteTexture;
    public Vector2 Position;
    Color mSpriteColor;
    public Rectangle Size;
    public string AssetName;
    private float mScale = 1.0f;

    public float Scale 
    {
        get { return mScale; }
        set
        {
            mScale = value;
            //Recalculate the Size of the Sprite with the new scale
            Size = new Rectangle(0, 0, (int)(mSpriteTexture.Width * Scale), (int)(mSpriteTexture.Height * Scale));
        }
    }

    public void LoadContent(ContentManager theContentManager, string theAssetName)
    {
        mSpriteTexture = theContentManager.Load<Texture2D>(theAssetName);
        AssetName = theAssetName;
        Size = new Rectangle(0, 0, (int)(mSpriteTexture.Width * Scale), (int)(mSpriteTexture.Height * Scale));
    }

    public  void Update(GameTime gameTime)
    {


    }

    public void Draw(SpriteBatch theSpriteBatch)
    {
         theSpriteBatch.Draw(mSpriteTexture, Position,
            new Rectangle(0, 0, mSpriteTexture.Width, mSpriteTexture.Height),
             Color.White, 0.0f, Vector2.Zero, Scale, SpriteEffects.None, 0);

        //theSpriteBatch.Draw(mSpriteTexture, Position);
    }
  }
}

敌人.cs

using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Storage;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using System;
using System.Collections.Generic;

namespace Lab05_2__Aaron_Benjamin_
{
    class Enemy : Sprite
{
    const string ENEMY_ASSETNAME = "gear";
    Random Rand = new Random();
    int startPos_X;
    int startPos_Y;

    public void LoadContent(ContentManager theContentManager)
    {
        Position = new Vector2(startPos_X = Rand.Next(0 , 1000), startPos_Y = Rand.Next(0, 1000)); //= Rand.Next(0, 100),Position.Y = Rand.Next(0,100));

        base.LoadContent(theContentManager, ENEMY_ASSETNAME);
    }

    public void Update(GameTime gameTime)
    {
        MouseState cState = Mouse.GetState();


        if (Position.X > cState.X)
        {
            Position.X += 1;
        }
        if (Position.X < cState.X)
        {
            Position.X -= 1;
        }
        if (Position.Y < cState.Y)
        {
            Position.Y -= 1;
        }
        if (Position.Y > cState.Y)
        {
            Position.Y += 1;
        }

        base.Update(gameTime);
       }        
     }
   }

Game1.cs

using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
namespace Lab05_2__Aaron_Benjamin_
{
/// <summary>
/// This is the main type for your game.
/// </summary>

public class Game1 : Game
{
    GraphicsDeviceManager graphics;
    SpriteBatch spriteBatch;
    List<Enemy> enemies = new List<Enemy>();




    private void CreateEnemy()
    {
        Enemy gear = new Enemy();
        Random rand = new Random();
        //gear = new Enemy();
        //gear.Position.X = rand.Next(0, 1000);
        //gear.Position.Y = rand.Next(0, 1000);
        Console.WriteLine(gear.Position.Y);
        enemies.Add(gear);

    }

    public Game1()
    {
        graphics = new GraphicsDeviceManager(this);
        Content.RootDirectory = "Content";
        IsMouseVisible = true;
    }

    /// <summary>
    /// Allows the game to perform any initialization it needs to before starting to run.
    /// This is where it can query for any required services and load any non-graphic
    /// related content.  Calling base.Initialize will enumerate through any components
    /// and initialize them as well.
    /// </summary>
    protected override void Initialize()
    {
        // TODO: Add your initialization logic here


        base.Initialize();
    }

    /// <summary>
    /// LoadContent will be called once per game and is the place to load
    /// all of your content.
    /// </summary>
    protected override void LoadContent()
    {
        // Create a new SpriteBatch, which can be used to draw textures.
        spriteBatch = new SpriteBatch(GraphicsDevice);

        // TODO: use this.Content to load your game content here
        for (int i = 0; i < 5; i++)
        {
            CreateEnemy();
        }

        foreach (var cog in enemies)
        {
            cog.LoadContent(this.Content);
        }
    }

    /// <summary>
    /// UnloadContent will be called once per game and is the place to unload
    /// game-specific content.
    /// </summary>
    protected override void UnloadContent()
    {
        // TODO: Unload any non ContentManager content here
    }

    /// <summary>
    /// Allows the game to run logic such as updating the world,
    /// checking for collisions, gathering input, and playing audio.
    /// </summary>
    /// <param name="gameTime">Provides a snapshot of timing values.</param>
    protected override void Update(GameTime gameTime)
    {
        if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.Escape))
            Exit();

        // TODO: Add your update logic here
        foreach (var cog in enemies)
        {
            if (cog.Position.X > Window.ClientBounds.Width - 50)
                cog.Position.X = Window.ClientBounds.Width - 50;
            if (cog.Position.Y > Window.ClientBounds.Height - 50)
                cog.Position.Y = Window.ClientBounds.Height - 50;

            if (cog.Position.X < 0)
                cog.Position.X = 0;
            if (cog.Position.Y < 0)
                cog.Position.Y = 0;
        }

        foreach (var cog in enemies)
        {
            cog.Update(gameTime);
        }

        if (Keyboard.GetState().IsKeyDown(Keys.M))
        {
            // If 'm' is down, we create a new meteor. Note that once this is working
            // this is going to make a lot of meteors. That's another issue, though.
            CreateEnemy();
        }
        //Console.WriteLine(enemies.Count);
        base.Update(gameTime);
    }

    /// <summary>
    /// This is called when the game should draw itself.
    /// </summary>
    /// <param name="gameTime">Provides a snapshot of timing values.</param>
    protected override void Draw(GameTime gameTime)
    {
        GraphicsDevice.Clear(Color.Black);

        // TODO: Add your drawing code here
        spriteBatch.Begin();
        foreach (var cog in enemies)
        {
           cog.Draw(spriteBatch);
        }
        spriteBatch.End();
        base.Draw(gameTime);
      }
   }
}

【问题讨论】:

    标签: c# object sprite monogame multiple-instances


    【解决方案1】:

    你不应该在这部分使用 gear 而不是 this.gear 吗?

     foreach (var gear in enemies)
     {
           this.gear.LoadContent(this.Content);
     }
    

    【讨论】:

    • 我的朋友刚刚注意到了这一点。我将所有这些更改为 cog 而不是 gear 并移动到创建实例的位置。它仍然只有一个精灵出现,但速度正确。有些东西告诉我随机位置不是每个精灵的新随机位置。我会更新代码。
    【解决方案2】:

    好的,我让它工作了。所以我的随机数被分配,然后在代码的不同部分重新分配,以便它们都堆叠在一起。这是解决方案。

    Sprite.cs

    class Sprite
    {
        Texture2D mSpriteTexture;
        public Vector2 Position;
        Color mSpriteColor;
        public Rectangle Size;
        public string AssetName;
        private float mScale = 1.0f;
    
        public float Scale 
        {
            get { return mScale; }
            set
            {
                mScale = value;
                //Recalculate the Size of the Sprite with the new scale
                Size = new Rectangle(0, 0, (int)(mSpriteTexture.Width * Scale), (int)(mSpriteTexture.Height * Scale));
            }
        }
    
        public void LoadContent(ContentManager theContentManager, string theAssetName)
        {
            mSpriteTexture = theContentManager.Load<Texture2D>(theAssetName);
            AssetName = theAssetName;
            Size = new Rectangle(0, 0, (int)(mSpriteTexture.Width * Scale), (int)(mSpriteTexture.Height * Scale));
        }
    
        public  void Update(GameTime gameTime)
        {
    
    
        }
    
        public void Draw(SpriteBatch theSpriteBatch)
        {
             theSpriteBatch.Draw(mSpriteTexture, Position,
                new Rectangle(0, 0, mSpriteTexture.Width, mSpriteTexture.Height),
                 Color.White, 0.0f, Vector2.Zero, Scale, SpriteEffects.None, 0);
    
            //theSpriteBatch.Draw(mSpriteTexture, Position);
        }
    
       }
    }
    

    敌人.cs

    class Enemy : Sprite
    {
        const string ENEMY_ASSETNAME = "gear";
        Random Rand = new Random();
        //int startPos_X;
        //int startPos_Y;
    
        public void LoadContent(ContentManager theContentManager)
        {
            Position = new Vector2(Position.X ,Position.Y);
    
            base.LoadContent(theContentManager, ENEMY_ASSETNAME);
        }
    
        public void Update(GameTime gameTime)
        {
            MouseState cState = Mouse.GetState();
    
    
            if (Position.X > cState.X)
            {
                Position.X += 1;
            }
            if (Position.X < cState.X)
            {
                Position.X -= 1;
            }
            if (Position.Y < cState.Y)
            {
                Position.Y -= 1;
            }
            if (Position.Y > cState.Y)
            {
                Position.Y += 1;
            }
    
            base.Update(gameTime);
        }        
      }
    }
    

    Game1.cs

    public class Game1 : Game
    {
        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;
        List<Enemy> enemies = new List<Enemy>();
        Random rand = new Random();
    
    
    
        private void CreateEnemy()
        {
            Enemy gear = new Enemy();
    
            //gear = new Enemy();
            gear.Position.X = rand.Next(0, 1000);
            gear.Position.Y = rand.Next(0, 1000);
            Console.WriteLine(gear.Position.Y);
            enemies.Add(gear);
            enemies[0].Position.X += 10;
    
        }
    
        public Game1()
        {
            graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";
            IsMouseVisible = true;
        }
    
        /// <summary>
        /// Allows the game to perform any initialization it needs to before starting to run.
        /// This is where it can query for any required services and load any non-graphic
        /// related content.  Calling base.Initialize will enumerate through any components
        /// and initialize them as well.
        /// </summary>
        protected override void Initialize()
        {
            // TODO: Add your initialization logic here
    
    
            base.Initialize();
        }
    
        /// <summary>
        /// LoadContent will be called once per game and is the place to load
        /// all of your content.
        /// </summary>
        protected override void LoadContent()
        {
            // Create a new SpriteBatch, which can be used to draw textures.
            spriteBatch = new SpriteBatch(GraphicsDevice);
    
            // TODO: use this.Content to load your game content here
            for (int i = 0; i < 5; i++)
            {
                CreateEnemy();
            }
    
            foreach (var cog in enemies)
            {
                cog.LoadContent(this.Content);
            }
        }
    
        /// <summary>
        /// UnloadContent will be called once per game and is the place to unload
        /// game-specific content.
        /// </summary>
        protected override void UnloadContent()
        {
            // TODO: Unload any non ContentManager content here
        }
    
        /// <summary>
        /// Allows the game to run logic such as updating the world,
        /// checking for collisions, gathering input, and playing audio.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Update(GameTime gameTime)
        {
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.Escape))
                Exit();
    
            // TODO: Add your update logic here
            foreach (var cog in enemies)
            {
                if (cog.Position.X > Window.ClientBounds.Width - 50)
                    cog.Position.X = Window.ClientBounds.Width - 50;
                if (cog.Position.Y > Window.ClientBounds.Height - 50)
                    cog.Position.Y = Window.ClientBounds.Height - 50;
    
                if (cog.Position.X < 0)
                    cog.Position.X = 0;
                if (cog.Position.Y < 0)
                    cog.Position.Y = 0;
            }
    
            foreach (var cog in enemies)
            {
                cog.Update(gameTime);
            }
    
            if (Keyboard.GetState().IsKeyDown(Keys.M))
            {
                // If 'm' is down, we create a new meteor. Note that once this is working
                // this is going to make a lot of meteors. That's another issue, though.
                CreateEnemy();
            }
            //Console.WriteLine(enemies.Count);
            base.Update(gameTime);
        }
    
        /// <summary>
        /// This is called when the game should draw itself.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(Color.Black);
    
            // TODO: Add your drawing code here
            spriteBatch.Begin();
            foreach (var cog in enemies)
            {
               cog.Draw(spriteBatch);
            }
            spriteBatch.End();
            base.Draw(gameTime);
        }
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-12-27
      • 2014-08-02
      • 2011-06-12
      • 2018-10-06
      • 2020-06-14
      • 1970-01-01
      相关资源
      最近更新 更多