我有问题。我已经尝试过如何使我的纹理移动,但我的解决方案很慢而且无法正常工作。有没有人知道如何使用C#XNAGamestudio进行texture2D移动。有人请帮助我!
修改
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();
}
答案 0 :(得分:4)
嗯,从技术上来说,这看起来似乎应该沿着X轴移动纹理。
至于表现,你可能想要考虑这些因素:
this.AddObject("Nameee", "C:\\Box.png");
。这不是一件好事。在LoadContent()方法中调用一次。Thread.Sleep(100);
跟踪已用时间,而不是使用GameTime
。 (如果您需要一个如何执行此操作的示例,请点击评论) Thread.Sleep(100);
,我建议使用相同的。{/ li>
醇>
另外,我建议完全重构此代码以获得更加面向对象的方法。创建一个包含Texture2D和Vector2的类。然后给它一个Update()方法和Draw(SpriteBatch sb)方法并在那里执行你的工作。
这只是一个建议。
答案 1 :(得分:3)
您可以执行与此类似的操作,并且应使用内容管理器加载资源。
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();
}
答案 2 :(得分:2)
Blau和justnS都给出了很好的答案。我还建议你看看一些XNA教程,以便更好地理解XNA框架及其应该如何使用(即单独的Initialize()
,LoadContent()
,{{1}的目的},Update()
等方法)。
首先尝试这些: