XNA中的动画

Max*_*kov 0 c# xna animation

我有这个代码:

        public class Area
{
    Texture2D point;
    Rectangle rect;
    SpriteBatch _sB;
    GameTimer _gt;
    int xo, yo, xt, yt;
    //List<Card> _cards;

    public Area(Texture2D point, SpriteBatch sB)
    {
        this.point = point;
        this._sB = sB;
        xt = 660;
        yt = 180;
        xo = 260;
        yo = 90;
    }

    public void Draw(SpriteBatch spriteBatch)
    {
        rect = new Rectangle(660, 180, 80, 120);
        spriteBatch.Draw(point, rect, Color.White);

        _gt = new GameTimer();
        _gt.UpdateInterval = TimeSpan.FromSeconds(0.1);
        _gt.Draw += OnDraw;
    }

    private void OnDraw(object sender, GameTimerEventArgs e)
    {
        this.pass(xo, yo);
        if (xo != xt) xo += (xt > xo) ? 10 : -10;
        if (yo != yt) yo += (yt > yo) ? 10 : -10;
    }

    public void pass(int x, int y)
    {
        rect = new Rectangle(x, y, 80, 120);
        _sB.Draw(point, rect, Color.Black);
    }
}
Run Code Online (Sandbox Code Playgroud)

所以,我无法理解什么是错的.这是我与XNA的第一个项目,因为它可能有愚蠢的错误:)

PS抱歉.有一个坐标(xt,yt)的矩形,我需要动画将矩形移动到(xo,yo)

PPS我添加了完整的课程更正,因为我不明白我的错误.

Bla*_*lau 5

你正在一帧中绘制整个动画..你应该从OnDraw调用带有不同x,y的Pass ...

编辑:

1)你不需要计时器,游戏类中的draw方法默认叫做每秒60帧......

2)Seconds参数应计算为(float)gametime.ElapsedTime.TotalSeconds;

float time;
int xt=660, yt=180;
int xo=260, yo=90;

public void Draw(SpriteBatch spriteBatch, float Seconds)
{
    rect = new Rectangle(660, 180, 80, 120);
    spriteBatch.Draw(point, rect, Color.White);

    this.pass(xo, yo, spriteBatch);
    time+= Seconds;
    if (time>0.3)
    {
        if (xo!=xt) xo+= (xt>xo) ? 10 : -10;
        if (yo!=yt) yo+= (yt>yo) ? 10 : -10;
        time = 0;
    }
}

public void pass(int x, int y, spritebatch sb)
{
    rect = new Rectangle(x, y, 80, 120);
    sb.Draw(point, rect, Color.Red);
}
Run Code Online (Sandbox Code Playgroud)

正如你应该知道的那样,这个动画会以粗略的方式移动...如果你想平滑地移动你的精灵......你可以使用Vector2作为你的位置,并使用浮动来获得你的速度;

Vector2 Origin = new Vector2(260, 90);
Vector2 Target = new Vector2(660, 180);
Vector2 Forward = Vector2.Normalize(Target-Source);
float Speed = 100; // Pixels per second
float Duration = (Target - Origin).Length() / Speed;
float Time = 0;

public void Update(float ElapsedSecondsPerFrame)
{
   if (Time<Duration)
   {
      Time+=Duration;
      if (Time > Duration) {
          Time = Duration;
          Origin = Target;
      }
      else Origin += Forward * Speed * ElapsedSecondsPerFrame;
   } 
}

public void Draw()
{
    rect = new Rectangle((int) Origin.X, (int) Origin.Y, 80, 120);
    sb.Draw(point, rect, Color.Red);   
}
Run Code Online (Sandbox Code Playgroud)