February 21, 2010

Making a character jump in XNA/C# (Basic Concept Included)

In the last tutorial, I briefly went over implementing gravity in games. By the end of the tutorial, we are going to program a character jumping when a key is pressed. I included 'Basic Concept Included' in the title because it doesn't use any XNA/C# specific stuff, just some simple math.

Jump?

Well, I'll first start off by telling you want happens in a 'jump'. First, upward force is applied and the character moves up. Somewhere down the road, gravity acts on it and it moves down.
I’m going to define all the variables in one go:
/*GraphicsDeviceManager, SpriteBatch, Texture2D and Vector2 may be found only in XNA. They are just used for drawing objects and defining locations.*/
GraphicsDeviceManager graphics; 
SpriteBatch spriteBatch;
Texture2D charr;
Vector2 charPos;
bool jumping; //Is the character jumping?
float startY, jumpspeed = 0; //startY to tell us //where it lands, jumpspeed to see how fast it jumps

Now, to the Initialize() function, provided by XNA:

charr = Content.Load<Texture2D>("ow"); //Load image
charPos = new Vector2(230, 450);//Char loc, X/Y
startY = charPos.Y;//Starting position
jumping = false;//Init jumping to false
jumpspeed = 0;//Default no speed

And the Update(), where the following is updated every frame:

//Init keyboard
KeyboardState keyState = Keyboard.GetState();
if (jumping)
{
    charPos.Y += jumpspeed;//Making it go up
    jumpspeed += 1;//Some math (explained later)
        if (charPos.Y >= startY)
        //If it's farther than ground
        {
            charPos.Y = startY;//Then set it on
               jumping = false;
        }
    }
else
{
    if (keyState.IsKeyDown(Keys.Space)) 
    {
        jumping = true;
        jumpspeed = -14;//Give it upward thrust
    }
}

We can now draw it with spriteBatch:

spriteBatch.Begin();
spriteBatch.Draw(charr, charPos, Color.White);
spriteBatch.End();

Explanation

We update charPos’s Y axis by jumpspeed. Since jumpspeed is set to –14 when space is pressed, this makes it go up (or down, depends on the game engine/platform you are using). Now, the magic- by adding 1 to jumpspeed every frame after, it will turn positive after a while and move down instead!
The value of jumpspeed will look like this:

-14,-13,-12….0,1,2,3….


If you have any questions, comments, or concerns, remember to leave me a comment. If you enjoyed the post, remember to Subscribe to my RSS feed. Or email me at finaiized(at)gmail.com if you want. I'm welcome to all suggestions you may have, and am willing to help you.

29 comments:

  1. Great tutorial, it helped a lot!

    ReplyDelete
    Replies
    1. EFFECTIVE AND POWERFUL LOVE SPELL CASTER AND LOTTERY SPELL 2019    GBOJIESPIRITUALTEMPLE@GMAIL. COM OR WHATSAPP HIM :+2349066410185 Hi i am from USA I have just experience the wonders of Dr. gbojie love spell, that have been spread on the internet and worldwide, How he marvelously helped people all over the world to restored back their marriage life and get back lost lovers, and also help to win lottery. I contacted him after going through so many testimonies from different people how he help to bring back ex lover back, i told him about my husband that abandoned me about 8 months ago, and left home with all i had.. Dr GBOJIE only told me to smile and have a rest of mind he will handle all in just 24 hours, After the second day my husband called me, i was just so shocked, i pick the call and couldn't believe my ears, he was really begging me to forgive him and making promises on phone.. He came back home and also got me a new car just for him to proof his love for me. i was so happy and called Dr Gbojie and thanked him, he only told me to share the good news all over the world .. Well if you need an effective and real spell caster contact Dr gbojie Via email: gbojiespiritualtemple@gmail.com, gbojiespiritualtemple@yahoo.com or Call or WhatsApp: +2349066410185 website : http://gbojiespiritualtemple.website2.me/  

      Delete
  2. I've looked at lots of jumping tutorials as I'm trying to make a platform game and this is by far the most useful I've come across.

    Not only does it work perfectly, you've explained it so simply as well whereas other places have dozens of lines of code and text yet fail to convey the necessary knowledge.

    Thank you very much :)

    ReplyDelete
  3. Best jumping tutorial I've found. Thanks alot!

    ReplyDelete
  4. This worked perfectly thank you sooooo much!!!

    ReplyDelete
  5. This comment has been removed by the author.

    ReplyDelete
  6. This comment has been removed by the author.

    ReplyDelete
  7. Very good tut! Only one thing... If you move your texture to a lower/higher position than the start position, the texture will jump from the original y position...

    If you move the line

    startY = charPos.Y;//Starting position

    from the Intialize() function to the last if statement - like this:

    if (keyState.IsKeyDown(Keys.Space))
    {
    jumping = true;
    jumpspeed = -14;//Give it upward thrust
    startY = charPos.Y;//Starting position
    }

    - your program will remember the Y position where you texture started :)

    ReplyDelete
  8. grate tutorial,helped alot ,but i have a proplem with my game , i want make my char to jump on a platfrom and can jump on other platforms can some1 help me with that??

    thank you

    ReplyDelete
  9. Thank you so much, been looking for somewhere that explains this without adding an entire library of their own code to the mix.

    Simple and concise, everything I needed

    ReplyDelete
  10. crap code. didnt help at all man

    ReplyDelete
  11. Thanks!
    Really useful and simple, helped a lot! :)

    ReplyDelete
  12. Amazing tut !! thank you very much !!

    ReplyDelete
  13. If you wanted to do this without XNA, in just C# express would it still work? I'm trying, but right now it isn't. I figure there is an error somewhere. My code is:
    //to recognize jump
    if (e.KeyData == Keys.Up)
    {
    blnJump = true;
    }
    //this is inside a timer with an interval of 1
    character.Top += vSpeed;
    vSpeed += 1;
    for (int i = 0; i < platforms.Length; i++)
    {
    if (character.Width > platforms[i].Left && character.Width < (platforms[i].Left+ 170) && character.Top >= (platforms[i].Top + 25))
    {
    blnJump = false;
    }
    }
    I am a beginner programmer, and hardly know anything at all. If anyone could help me here, I would be grateful.

    ReplyDelete
  14. Awesome tutorial, works 100%, congratulations dude.

    ReplyDelete
  15. Great tutorial! I just cannot seem to apply it to my game - maybe im just stupid, however please help someone!!! Here's my sprite code: *Help Appreciated!*
    class AnimatedSprite
    {
    KeyboardState currentKBState;
    KeyboardState previousKBState;
    Texture2D spriteTexture;
    float timer = 0f;
    float interval = 20f;
    int frame=1;
    int RunFrame = 194;
    int JumpFrame = 56;
    int spriteWidth = 56;
    int spriteHeight = 70;
    Vector2 spriteVelocity = Vector2.Zero;
    public Rectangle sourceRect;
    Vector2 position;
    Vector2 origin;
    int yPos;
    private SpriteEffects effect = SpriteEffects.None;
    public Vector2 Position
    {get { return position; }
    set { position = value; }}
    public Vector2 Origin
    {get { return origin; }
    set { origin = value; }}
    public Texture2D Texture
    {get { return spriteTexture; }
    set { spriteTexture = value; }}
    public Rectangle SourceRect
    {get { return sourceRect; }
    set { sourceRect = value; }}
    public AnimatedSprite(Texture2D texture, int frame, int spriteWidth, int spriteHeight)
    {this.spriteTexture = texture;
    this.frame = frame;
    this.spriteWidth = spriteWidth;
    this.spriteHeight = spriteHeight;}
    public void HandleSpriteMovementLeftRight(GameTime gameTime)
    {
    previousKBState = currentKBState;
    currentKBState = Keyboard.GetState();

    if (currentKBState.IsKeyDown(Keys.Left))
    {
    spriteVelocity.X = 20.0f;
    frame = RunFrame;
    yPos = 214;
    }
    else if (currentKBState.IsKeyDown(Keys.Right))
    {
    spriteVelocity.X = 20.0f;
    frame = RunFrame;
    yPos = 214;
    }
    else if (currentKBState.IsKeyDown(Keys.Up))
    {
    spriteVelocity.Y = 20.0f;
    frame = JumpFrame;
    yPos = 280;
    }
    else if (currentKBState.IsKeyDown(Keys.Down))
    {
    spriteVelocity.Y= 20.0f;
    frame = JumpFrame;
    yPos = 280;
    }
    sourceRect = new Rectangle(frame * spriteWidth, yPos, spriteWidth, spriteHeight);

    ReplyDelete

  16. if (currentKBState.GetPressedKeys().Length == 0)
    {
    if (RunFrame > 0 && RunFrame < 12)
    {
    RunFrame= 0;
    }
    }
    if (Position.X < 800 && currentKBState.IsKeyDown(Keys.Right))
    {
    AnimateRight(gameTime);
    position.X += spriteVelocity.X;
    effect = SpriteEffects.None;
    }
    if (position.X > 2 && currentKBState.IsKeyDown(Keys.Left))
    {
    AnimateLeft(gameTime);
    position.X -= spriteVelocity.X;
    effect = SpriteEffects.FlipHorizontally;
    }
    if (position.Y < 370 && currentKBState.IsKeyDown(Keys.Down))
    {
    AnimateDown(gameTime);
    position.Y += spriteVelocity.Y;
    }
    if (position.Y > 0 && currentKBState.IsKeyDown(Keys.Up))
    {
    AnimateUp(gameTime);
    position.Y -= spriteVelocity.Y;
    }
    origin = new Vector2(sourceRect.Width / 2, sourceRect.Height / 2);

    }
    public void AnimateRight(GameTime gameTime)
    {
    if (currentKBState != previousKBState)
    {
    RunFrame = 4;
    }
    timer +=
    (float)gameTime.ElapsedGameTime.TotalMilliseconds;

    if (timer > interval)
    {
    RunFrame++;

    if (RunFrame > 7)
    {
    RunFrame = 4;
    }
    timer = 0f;
    }
    }
    public void AnimateLeft(GameTime gameTime)
    {
    if (currentKBState != previousKBState)
    {
    RunFrame = 4;
    }
    timer +=
    (float)gameTime.ElapsedGameTime.TotalMilliseconds;
    if (timer > interval)
    {
    RunFrame++;
    if (RunFrame > 7)
    {
    RunFrame = 4;
    }
    timer = 0f;
    }
    }
    public void AnimateDown(GameTime gameTime)
    {
    if (currentKBState != previousKBState)
    {
    JumpFrame = 2;
    }
    timer +=
    (float)gameTime.ElapsedGameTime.TotalMilliseconds;

    if (timer > interval)
    {
    JumpFrame++;
    if (JumpFrame > 5)
    {
    JumpFrame = 2;
    }
    timer = 0f;
    }
    }
    public void AnimateUp(GameTime gameTime)
    {
    if (currentKBState != previousKBState)
    {
    JumpFrame = 2;
    }
    timer +=
    (float)gameTime.ElapsedGameTime.TotalMilliseconds;

    if (timer > interval)
    {
    JumpFrame++;

    if (JumpFrame > 5)
    {
    JumpFrame = 2;
    }
    timer = 0f;
    }
    }
    public void Draw(SpriteBatch spriteBatch, GameTime gameTime)
    {spriteBatch.Draw(spriteTexture, Position, sourceRect, Color.White, 0f, Origin, 1.0f, effect, 0);}
    }
    }

    ReplyDelete
  17. sorry the anonymous and joanne comments are mine...full code between two comments!

    ReplyDelete
  18. I am suге this aгtіcle has toucheԁ all
    the іnternet people, its really гeally good post on building up new wеb site.


    Visit my homepage :: estrip.co.kr

    ReplyDelete
  19. I wοulԁ not put it іn the fгeezеr fοг a long time, you can put it
    in the frеezеr for a couple of houгѕ but I would not put it in thегe for a сouρle οf weeks.

    From there we mονed on tο
    dinner, a ѕtаggeгіng sрrеаd of
    mouth-watеring οptions рrepаred for us
    by lοcal гestaurant legenԁ 5 & 10.
    It also сontains aѕorbic acіd, beet pοwder,
    drу уеast, defatted soy flouг,
    maliс aciԁ, monοcalcіum phoѕphate,
    modifіеd сorn ѕtaгсh,
    naturаl flavors, гehуdrated enzymе modified сheese,
    sodium bicarbonate, ѕoгbitan monѕtеarаte, аnd xanthаn gum.


    my page pizza stone

    ReplyDelete
  20. Howdy! I understand this is sort of off-topic but I had to ask.
    Does building a well-established blog such as yours take a large amount of work?
    I'm brand new to writing a blog but I do write in my journal on a daily basis. I'd like to start a blog so I
    will be able to share my experience and views online.
    Please let me know if you have any kind of suggestions or
    tips for new aspiring bloggers. Thankyou!

    Check out my weblog; home loans for Bad credit

    ReplyDelete
  21. I'm impressed, I must say. Rarely do I encounter a blog that's both educative and
    amusing, and without a doubt, you have hit the nail on the head.

    The issue is something that not enough men and women are speaking intelligently
    about. I'm very happy that I found this in my search for something relating to this.

    Also visit my web-site :: workouts to increase vertical leap

    ReplyDelete
  22. Nice blog here! Additionally your website so much up very fast!

    What host are you the usage of? Can I am getting your associate hyperlink
    to your host? I desire my website loaded up as quickly as yours lol

    Also visit my weblog :: workouts for vertical

    ReplyDelete
  23. thanks a lot for this tutorial! just to help you out a bit: add captcha for anonymous posts, note the spam above :(

    ReplyDelete
  24. thanks for the tutorial..it works perfectly =)

    ReplyDelete
  25. if this works, ill give 5 stars....for now just hang on

    ReplyDelete