在曲线上移动矩形

时间:2013-12-06 18:11:12

标签: c# xna

public class Game1 : Microsoft.Xna.Framework.Game
{
    GraphicsDeviceManager graphics;
    SpriteBatch spriteBatch;
    Vector2 initialpos = new Vector2(0,400);
    Vector2 initialvel = new Vector2(100,-50);
    Vector2 acc = new Vector2(0,100f);
    Texture2D image1,wall,wall2;
    float time = 0;
    Vector2 pos,wallpos,wall2pos;
    Rectangle posrec,wallrec;
    KeyboardState keystat;

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

    protected override void Initialize()
    {
        pos = new Vector2(40,90);
        wallpos = new Vector2(480,350);
        wall2pos = new Vector2(200, 200);
        posrec = new Rectangle(40,90,20,20);
        wallrec = new Rectangle(480,350,20,80);
        base.Initialize();
    }

    protected override void LoadContent()
    {
        spriteBatch = new SpriteBatch(GraphicsDevice);
        image1 = Content.Load<Texture2D>("Sprites/sprite");
        wall2 = Content.Load<Texture2D>("Sprites/wall2");
        wall = Content.Load<Texture2D>("Sprites/wall");
    }

    protected override void Update(GameTime gameTime)
    {
        if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.Escape))
            this.Exit();

        keystat = Keyboard.GetState();

        time += (float)gameTime.ElapsedGameTime.TotalSeconds;
        pos = initialpos + initialvel * time + 0.10f * acc * time * time;
        if(posrec.Intersects(wallrec))
            spriteBatch.Draw(wall2,wall2pos,Color.White);
        base.Update(gameTime);
    }

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

        spriteBatch.Begin();
        spriteBatch.Draw(wall, wallpos, wallrec, Color.White);
        spriteBatch.Draw(image1, pos, posrec, Color.White);
        spriteBatch.End();
        base.Draw(gameTime);
    }
}

当我使用Vector2使纹理移动到特定曲线时它很好但是当我使用矩形位置将纹理移动到特定曲线时,我的纹理不会移动。请帮助,我有Rectangle而不是Vector2,以便我可以检测到碰撞。

1 个答案:

答案 0 :(得分:0)

您正在使用Draw的重载:

public void Draw (
     Texture2D texture,
     Vector2 position,
     Nullable<Rectangle> sourceRectangle,
     Color color
)

我认为这不是你想要的。

第三个参数定义纹理中的源纹理元素,这意味着将绘制纹理的区域。如果要绘制整个纹理,该参数应始终为null

你可能需要这个:

public void Draw (
     Texture2D texture,
     Rectangle destinationRectangle,
     Color color
)

destinationRectangle指定(在屏幕坐标中)绘制精灵的目的地。