I’m trying to make a jumping mechanism in my game which will work something like this:
// velocity.Y is the velocity of the sprite I want to jump
if (keystate.IsKeyDown(Keys.W))
{
velocity.Y = 3 - (time elapsed since start of jump);
}
I thought this might be a simple and elegant solution to making my sprite jump but if it is not possible like this just say so and it’s back to the drawing board.
I would suggest not connecting the physics so directly to the player input, it’s not a very extendable architecture.
Have an interface which defines physics properties such as velocity which is implemented by your character object. When the player presses the up-key you should check if the player is on the ground, if they are then set their acceleration to move up. Then have a physics system iterate through a list of every object which implements the physics interface applying gravity and other forces before moving the entities around. This way you can use the same physics code for every entity in your game.
I would also suggest not connecting keyboard input directly to the movement of the player. You can have an interface called ‘ICharacterController’ which defines a ‘nextInstruction’ method which returns ‘CharacterInstructions’ which defines various actions characters can take such as jumping and moving, this can be implemented by an input class. Your character class then holds a reference to a CharacterController so it just calls nextInstruction, this way the character can be controlled by Player Input, AI, or through network communication but still share the same behavior as the player.
Game Coding Complete is a brilliant book to read if you’re serious about game programming.
I can also recommend Game Engine Architecture
As you’re using XNA you should consider using Game Components