如何用重力使精灵弹跳?

时间:2011-10-09 09:54:12

标签: sprite gravity bounce

好的,所以我一直在关注花车的教程,并让精灵以一定的速度移动 每帧低于1个像素。满容易。现在,我得到以下任务:

  

为计算新坦克的位置增加重力影响,   让它自动降落而不是反弹顶部   每一次。

我如何制作这种重力的东西?我只学会了如何添加到x和y ...... 当然,简单地将每个帧添加到y值不能很好地工作,并且不是真的 重力。我真的没有得到我期望在这里做的事情。

要了解简短教程,请点击链接。这很简单。 http://www.devmaster.net/articles/intro-to-c++-with-game-dev/part6.php

这是我的错误代码,让坦克在四个方向上移动并使其无形 什么时候下来由于教程,我添加了浮点数。

 Sprite theSprite( new Surface("assets/ctankbase.tga"), 16 );


        float SpriteX = 50;
    float SpriteY = 0;    //the sprite starts at the top of the screen (2D coords system)
    float screenBottom = 400; //I'm assuming your screen is 200 pixels high, change to your size
    float speedY = 0.01; //the initial speed of the sprite
    float accelY = 0.01;  //the change in speed with each tick
    bool  Bottom = false;

    void Game::Tick( float a_DT )
    {
        m_Screen->Clear( 0 );

        theSprite.Draw(SpriteX, SpriteY, m_Screen ); // Draws sprite


        if(SpriteY >= screenBottom) //when we hit bottom we change the direction of speed and slow it
        {
            speedY = -speedY/2;
            Bottom = true;
        }

        if(Bottom == false)
        {
        SpriteY += speedY;
        }

        speedY += accelY;

    }

那么我怎样才能让这个坦克以“重力”在屏幕上反弹,减少代码? 谢谢。对不起,如果这是一个愚蠢的问题,但我没有看到它。

3 个答案:

答案 0 :(得分:2)

当我需要各种“重力”(也可能仅称为加速度向下)时,我通常会做的是定义positionspeedacceleration变量。你向speed添加position的每个刻度,这样你的精灵每次滴答都会在给定的方向上移动,现在你还需要改变speed以使运动方向逐渐变化,这就是在acceleration进来的地方,您可以在每个刻度线上将其添加到speed

伪代码如下所示:

var posy = 50;
var speedy = 5;
var accely = -0.5;
tick() {
    posy += speedy;
    speedy += accely;
}

这样你的速度最终会变为负值,因此会开始移动精灵底部而不是向上移动。

注意:我的值是任意的,你必须使用它们才能达到你真正需要的效果

这是我认为适合你的情况的代码,为简单起见,我假设你的球只在Y轴上移动。您必须自己添加X轴运动。

float SpriteX = 50;
float SpriteY = 100;    //the sprite starts at the top of the screen (2D coords system)
float screenBottom = 200; //I'm assuming your screen is 200 pixels high, change to your size
float speedY = 0.23; //the initial speed of the sprite
float accelY = 0.02;  //the change in speed with each tick

void Game::Tick( float a_DT )
{
    m_Screen->Clear( 0 );

    theSprite.Draw(SpriteX, SpriteY, m_Screen ); // Draws sprite


    if(SpriteY >= screenBottom) //when we hit bottom we change the direction of speed and slow it
    {
        speedY = -speedY/2;
    }
    SpriteY += speedY;
    speedY += accelY;
}

此代码根本没有经过测试,因此可能需要使用它才能使其真正起作用。值也是任意的,但逻辑保持不变。我试图删除所有与弹跳没有直接关系的东西,让我知道它是如何工作的。

希望这会有所帮助。

答案 1 :(得分:0)

它只是简单的物理学。

您需要一个位置和速度的变量。速度随着时间的推移会线性增加,因此您只需在每帧添加一个常量。然后将速度添加到位置,您将获得相应的万有引力行为。

答案 2 :(得分:0)

您需要跟踪精灵的当前速度。

在每次迭代时,你必须为速度添加一个常量(这个常数是加速度),然后绘制精灵,好像它已根据当前速度移动,即将速度添加到当前位置。当然,为了获得好看的效果,速度和加速度应该是2维矢量。

在地球上,引力是一个加速度,其值9.81 m/(sec^2)指向地球。这意味着每一秒物体的速度在地球的方向上增加9.81 m/s