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.