我不能让我的精灵移动

时间:2012-11-07 22:35:16

标签: c# xna sprite

我是XNA的新手,我目前正在学习本教程:

http://msdn.microsoft.com/en-us/library/bb203893.aspx

在完成第5步后运行程序时出现问题。我不认为这是一个错字,因为其他人在评论中指出了同样的问题。

我的精灵在程序运行时会自动在屏幕上反弹,但是甚至不会从0,0移动像素。

using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;

namespace WindowsGame1
{

public class Game1 : Microsoft.Xna.Framework.Game
{
    GraphicsDeviceManager graphics;
    SpriteBatch spriteBatch;

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


    protected override void Initialize()
    {


        base.Initialize();
    }

    Texture2D myTexture;

    Vector2 spritePosition = Vector2.Zero;

    Vector2 spriteSpeed = new Vector2(50.0f, 50.0f);

    protected override void LoadContent()
    {

        spriteBatch = new SpriteBatch(GraphicsDevice);
        myTexture = Content.Load<Texture2D>("Main");

    }


    protected override void UnloadContent()
    {

    }


     void UpdateSprite(GameTime gameTime)
    {
        //Move the sprite by speed, scaled by elapsed time

         spritePosition +=
            spriteSpeed * (float)gameTime.ElapsedGameTime.TotalSeconds;

        int MaxX =
            graphics.GraphicsDevice.Viewport.Width - myTexture.Width;
         int MinX = 0;

         int MaxY =
             graphics.GraphicsDevice.Viewport.Height - myTexture.Height;
         int MinY = 0;

         //Check for bounce.
         if (spritePosition.X > MaxX)
         {
             spriteSpeed.X *= -1;
             spritePosition.X = MaxX;

         }

         else if (spritePosition.X < MinX)
         {
             spriteSpeed.X *= -1;
             spritePosition.X = MinX;

         }

         if (spritePosition.Y > MaxY)
         {
             spriteSpeed.Y *= -1;
             spritePosition.Y = MaxY;
         }

         else if (spritePosition.Y < MinY)
         {
             spriteSpeed.Y *= -1;
             spritePosition.Y = MinY;
         }


    }


    protected override void Draw(GameTime gameTime)
    {
        GraphicsDevice.Clear(Color.CornflowerBlue);



        spriteBatch.Begin(SpriteSortMode.BackToFront, BlendState.AlphaBlend);
        spriteBatch.Draw(myTexture, spritePosition, Color.White);
        spriteBatch.End();

        base.Draw(gameTime);
    }
  }
}

1 个答案:

答案 0 :(得分:4)

不会从任何地方调用UpdateSprite方法......

您应该覆盖Update方法并从那里调用UpdateSprite方法......

编辑:

将此添加到您的游戏类:

protected override void Update(GameTime gameTime)
{
    UpdateSprite(gameTime);
}