user35443
user35443

Reputation: 6403

How to make texture move

I have problem. I have tryed how to make my texture move, but my solution is slow and it is not working. Does anybody know how to make texture2D move using C# XNAGamestudio. ANybody please help me!

EDIT:

GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;
        public Hashtable Objects = new Hashtable();
        public Hashtable XPOS = new Hashtable();
        public Hashtable YPOS = new Hashtable();
        public int NUM = 0;
        public bool UP = true;
        public bool DOWN = false;
        public bool LEFT = false;
        public bool RIGHT = false;
  ......
protected override void Update(GameTime gameTime)
        {
            // Allows the game to exit
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
                this.Exit();
            this.AddObject("Nameee", "C:\\Box.png");
            // TODO: Add your update logic here
            if (UP)
            {
                if (NUM != 25)
                {
                    AppendObject(new Vector2((float)this.XPOS["Nameee"], (float)this.XPOS["Nameee"] - NUM), "Nameee");
                    NUM++;
                    Thread.Sleep(100);
                }
                else
                    UP = false;
            }
            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.CornflowerBlue);
            //spriteBatch.Begin();

            //spriteBatch.End();


            //base.Draw(gameTime);
        }
        public void AddObject(string TagName, string ObjectImage)
        {
            Texture2D fileTexture;
            using (FileStream fileStream = new FileStream(@ObjectImage, FileMode.Open))
            {
                fileTexture = Texture2D.FromStream(graphics.GraphicsDevice, fileStream);
            }
            if (!this.Objects.ContainsKey(TagName))
            {
                this.Objects.Add(TagName, fileTexture);
                this.XPOS.Add(TagName, 0.0F);
                this.YPOS.Add(TagName, 50.0F);
            }
        }
        public void AppendObject(Vector2 pos, string tagName)
        {
            spriteBatch.Begin();
            spriteBatch.Draw((Texture2D)this.Objects[tagName], new Vector2((float)this.XPOS[tagName], (float)this.YPOS[tagName]), Color.White);
            spriteBatch.End();
        }

Upvotes: 2

Views: 921

Answers (3)

Blau
Blau

Reputation: 5762

You can do something similar to this, and you should use the content manager to load assets.

public class Sprite
{
    public Vector2 Position = Vector2.Zero;
    public Texture2D Texture;
    public float Scale = 1;


    public void LoadAsset(Game game, string asset)
    {
         Texture = game.Content.Load<Texture2d>(asset);
    } 

    public Draw(SpriteBatch batch)
    {
        batch.Draw(Texture, Position, null, Color.White, ...,... Scale,...);
    }
}


//In your game:

List<Sprite> Sprites = new List<Sprite>();

Initialize()
{
    base.Initialize();
    Sprite myBox = new Box();
    myBox.LoadAsset("Box"); 
    Sprites.Add(myBox);
}


Update(GameTime gametime)
{
    myBox.Position += Vector2.UnitX * Speed * (float) gametime.elapsed.TotalSeconds;
}


Draw()
{
    batch.begin();
    foreach (Sprite sprite in Sprites) sprite.Draw(batch);
    batch.end();   
}

Upvotes: 3

Samuel Slade
Samuel Slade

Reputation: 8613

Both good answers by Blau and justnS. I would also advise to take a look at some XNA tutorials to get a better understanding of the XNA Framework and how it should be used (i.e. the purpose of the separate Initialize(), LoadContent(), Update(), Draw(), etc methods).

Try these for starters:

Upvotes: 2

Justin Self
Justin Self

Reputation: 6265

Hmm, well technically, this looks like it should move a texture along the X axis.

As for performance, you may want to take these things into consideration:

  1. You are calling this.AddObject("Nameee", "C:\\Box.png"); on every update. That's not a good thing. Call this once in your LoadContent() method.
  2. Instead of using Thread.Sleep(100);, I would suggest tracking the time elapsed with GameTime. (Hit the comment if you need an example of how to do this)
  3. You are creating a new vector2 on each pass for the texture position. While this probably doesn't have a noticeable performance hit since its only creating 10 a second (thanks to your Thread.Sleep(100);, I would suggest using the same one.

On a side note, I would recommend completely refactoring this code for a more object oriented approach. Create a class that holds a Texture2D and a Vector2. Then give it an Update() method and a Draw(SpriteBatch sb) method and perform your work in there.

That's just a suggestion though.

Upvotes: 4

Related Questions