The logic of the transition to the game

I am creating a 2D Mario game.

The following function is designed to update the player’s position when a certain key is pressed. The player is allowed to move left and right, jump in the same place or jump left or right (form like an arc).

bool updatePlayerPosition(Movement* mov){ if (this->keyPressed(SDLK_RIGHT)) { mov->applyForce(1); // Changes the velocity in X } if (this->keyPressed(SDLK_LEFT)) { mov->applyForce(-1); // Changes the velocity in X } if (this->keyPressed(SDLK_SPACE)) { mov->jump(); // Changes the velocity in Y } if (this->keyPressed(SDLK_DOWN)) { mov->fallDown(); // Changes the velocity in X and Y } Point* pos = mov->getPosition(); // Check whether the position is out of bounds if(Level::allowsMove(pos)){ // If it is not, I update the player current position position->x = pos->x; position->y = pos->y; return true; } // If the movement is not allowed, I don't change the position else { mov->setPosition(*position); return false; } } 

Here's the mistake: when I hit the end of the level (which has a fixed width), and if I try to move to the right and jump at the same time , the player jumps and stays in the air. Only when I unlock the space does the player come to the ground.

How can i fix this?

+4
source share
2 answers

For your game, I think you want the player to hop whenever the space is pressed and when the player is on the floor. Then you must check if the player is on the floor in order to have the desired behavior.

I offer you a device with this mechanism:

 if (this->keyPressed(SDLK_SPACE) && this->isOnTheFloor()) { ^^^^^^^^^^^^^^^^^^^^^^^ mov->jump(); // Changes the velocity in Y } 
+2
source

Your space handler should use force only once - when you press the key or up, if you want, and not in every frame. In the white space panel, the "up" speed should be set to some (likely constant) value. Then each frame, if not on the ground, the speed down should increase the specified number at maximum speed. So, OnSpacebarDown, YVelocity = 10.0; and for each frame if(!bGrounded) YVelocity -= 1.0;

0
source

Source: https://habr.com/ru/post/1441444/


All Articles