Game jump logic - c++

I am creating a 2D Mario game.
The following function is intended to update a player's position when a particular key is pressed. The player is allowed to move left and right, and jump in the same place, or jump to the left or to the right (to 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's 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 is the bug: when I hit the end of the level (which has a fixed width), and if I try to move right and jump at the same time, the player jumps and stays in the air. Only when I release the space bar does the Player come to the ground.
How can I fix this?

For your game, I think you only want the player to jump whenever space is pressed and when the player is on the floor. You must then check if the player is on the floor to have the desired behavior.
I suggest you device a mechanism like this:
if (this->keyPressed(SDLK_SPACE) && this->isOnTheFloor()) {
^^^^^^^^^^^^^^^^^^^^^^^
mov->jump(); // Changes the velocity in Y
}

Your spacebar handler should only apply force one time - on key down, or up, if you prefer, not every frame. On spacebar down, velocity 'up' should be set to some (likely constant) value. Then every frame, if not on the ground, velocity down should be increase a specified amount, with a maximum speed. So OnSpacebarDown, YVelocity = 10.0; and for each frame if(!bGrounded) YVelocity -= 1.0;

Related

box2d falling while moving

Hey my player isn't falling while I'm pressing any of movement inputs while I'm falling. Just stands still and moves right or left.
Just watch the video; Video
My movement code;
if (right == true) {
p_pBody.body->SetLinearVelocity(b2Vec2(5, 0));
}
else
{
p_pBody.rect.setPosition(p_xPos * s_METPX, p_yPos * s_METPX); // Set The SFML Graphics
}
if (left == true) {
p_pBody.body->SetLinearVelocity(b2Vec2(-5, 0));
}
else
{
p_pBody.rect.setPosition(p_xPos * s_METPX, p_yPos * s_METPX); // Set The SFML Graphics
}
You're setting the vertical velocity to 0 when you're pressing right or left. That's the second coordinate of b2Vec2. If you want to have gravity, replace that zero with the vertical velocity the block has when the buttons are not being pressed.

How to get unreal engine Touch Index type in C++?

I added touch input for my game's character. The camera moves when a player's finger is dragged across the screen. However, when the joysticks are used to move, the camera doesn't move at the same time.
When I do the same code with Blueprints the code works and the camera still moves. When I drag the touch while pressing the joystick to move, I think that there is a problem in the ETouchIndex::Type. This is because in the BP when I use the finger index given in the touch event, it works. However, when I only use touch 1 as the finger index, it does not work. I think if I put that index in my CPP code it will work too, but where can I find the finger index? Can anyone please help me?
//here's my touch code that executes every tick.
FVector2D TouchLocation;
APlayerController* ActivePlayerController = UGameplayStatics::GetPlayerController(this, 0);
ActivePlayerController->GetInputTouchState(TouchType, TouchLocation.X, TouchLocation.Y, IsTouched);
if (!IsTouched)
{
DidOnce = false;
}
if (IsTouchMoved())
{
if (!DidOnce)
{
ActivePlayerController->GetInputTouchState(TouchType, PrevX, PrevY, IsTouched);
DidOnce = true;
}
ActivePlayerController->GetInputTouchState(TouchType, X, Y, IsTouched);
float FinalRotYaw = (X - PrevX) * UGameplayStatics::GetWorldDeltaSeconds(this) * 20;
float FinalRotPitch = (Y - PrevY) * UGameplayStatics::GetWorldDeltaSeconds(this) * 20;
AddControllerYawInput(FinalRotYaw);
AddControllerPitchInput(FinalRotPitch);
ActivePlayerController->GetInputTouchState(TouchType, PrevX, PrevY, IsTouched);
}

CCSprite Not Flipping

So in my game I am trying to make the character be able to go left or right depending on the button the player pushes.
I want to flip the sprite so that it faces the right way in whatever direction it is going.
I have a bool as a property of the player class called isGoingLeft and thats how I check when the player is facing left.
The way I flip the player is like this
//IN THE METHOD FOR THE RIGHT BUTTON
if (player.isGoingLeft) {
player.flipX = 180;
NSLog(#"Flip Right");
player.isGoingLeft = FALSE;
}
//IN THE METHOD FOR THE LEFT BUTTON
if (!player.isGoingLeft) {
player.flipX = 180;
player.isGoingLeft = TRUE;
NSLog(#"Flip Left");
}
This works when I start off going right, and then turn left (the sprite flips correctly). But when I try to go right again, the player moves right, it just doesn’t flip again. The NSLog saying that it flipped back to facing right runs and the bool is changed. I have no idea what is going on
flipX is a BOOL type, so any value greater than 0 will make the sprite flipped.
Use this instead:
player.flipX = YES;
player.flipX = NO;

C++ Collision Detection doesn't work on last check?

Over the last few days I have been trying to implement simple collision detection of objects drawn using OpenGL.
With the aid of the Pearson, Computer Graphics with OpenGL I have managed to write the following function:
void move(){
if(check_collision(sprite,platform1) || check_collision(sprite,platform2)){ //if colliding...
if (downKeyPressed ){ y_Vel += speed; downKeyPressed = false;} //going down
else if(upKeyPressed ){ y_Vel -= speed; upKeyPressed = false;} //going up
else if(rightKeyPressed){ x_Vel -= speed; rightKeyPressed = false;} //going right
else if(leftKeyPressed ){ x_Vel += speed; leftKeyPressed = false;} //going left
} // always glitches on whatever is last else if above?!?!
else{ glTranslatef(sprite.x+x_Vel, sprite.y+y_Vel, 0.0); }
}
My sprite moves in accordance to keyboard inputs (the arrow keys). If it collides with a stationary object it stops moving and stays in its position.
So far, it works when colliding with the top, left side and bottom of the stationary object. Unfortunately (even though I use the same logic) the right hand side doesn't work and upon a collision the sprite is redrawn at its original x/y coordinates. I'm baffled.
As it turns out, which-ever is the last check in the move() function (the last else-if) is the one that doesn't work... I have swapped the left with the right and sure enough when left is then the last one and the one that plays up :(
Any advice or ideas on how I can improve this and stop it glitching?
Please excuse my naivety and amateur coding. I'm merely a self-taught beginning. Thanks.
You should not use an else if. There is a possibility that it is hitting a side and the top or the bottom in the same frame. Trying changing those to all ifs because you want to check each one. or at the least change it to this.
if( /* check top */)
{
}
else if( /* check bot */)
{
}
if( /* check right */ )
{
}
else if( /* check left */)
{
}
Also, you should avoid declaring global variables like Y_VEL and X_VEL as this creates confusion. You may just be doing this to get your feet wet but I would avoid it. Create a class for each object and then have the velocities as members of that class.
Well, it seems to me that you have an issue when it comes to translating the actual object.
Your move code states
if(there is a collision)
{
//do stuff
}
else
{
glTranslateF( );
}
SO, whenever there is a collision, the translate function never gets called.
My opinion is that you should pull the glTranslateF() call out of the else {...}, just have it get called every time. However, it seems you're using the exact same 'draw' function for every rectangle, not just the player sprite. You'll probably have to ind a way to distinguish between regular rectangles (such as the platforms) and the player rectangle. Perhaps the simplest way for you to implement this, would be to have two different drawSprite functions: one for regular platforms, and the other for the player. Only call the move() function from within the player's draw function (perhaps called drawPlayer()?)
I don't quite have the time to look over all of your code to make a more educated and specific suggestion at the moment; however, I'll be free later this evening if this question is still open and needing help.
As you've already figured out, the problem is related to glTranslate(). Since you operate on both sprite's position and velocity, you should repeatedly update the positions using the velocities. That is:
sprite.x += x_vel;
sprite.y += y_vel;
and do it simply all the time (i.e. by some timer or every frame, if the scne is redrawn repeatedly). A collision then is equivalent to changing the velocity vector (x_vel, y_vel) in some way to simulate the collision effect: either zero it to stop any movement at all, or change the velocity component sign (x_vel = -x_vel) to make it rebound in an absolutely elastic manner, or do something else that fits.
What happens now with glTranslate() is that x_vel, y_vel actually hold offsets from the starting position, but not velocities of movement.

Reverse animation direction when hitting the side of the screen

I am creating a space invaders game for my university assignment. I am breaking the parts down on paper, I thought a good place to start would be to move the sprites across the screen. The issue I have at the moment is this, when the sprite his the right hand side of the screen it would just carry on moving, so I added this code:
if (invadersSprite.getPosition().x > 650)
{
std::cout << "WIDTH_END" << std::endl;
}
I basically used this for debugging for future reference. The output popped up into the console so I knew I was onto something. So, I started moving on from the output to actually moving the sprites back to the left hand side of the screen. I am now having more issues then expected.
I declared some ints for up, left, right and down just for easability when it comes to reading the code.
int spriteWalkSpeed = 50;
int up=-spriteWalkSpeed, down=spriteWalkSpeed, left=-spriteWalkSpeed, right=spriteWalkSpeed;
I've tried using the SFML move commands and also setPosition, but none of them really work as I thought they should.
move:
The issue I have had with this one is it basically stops in the middle of the screen. It still animates the leg movement and such, but it doesn't move left or right.
if (invadersSprite.getPosition().x > 650)
{
invadersSprite.move(left, 00);
}
setPosition:
This is a little closer to what I am after, but still no cigar. The movement pauses for around a second and then pops up at the left hand side of the screen. What I need is to move back down the screen.
if (invadersSprite.getPosition().x > 650)
{
invadersSprite.setPosition(left, 00);
}
I haven't been using SFML for very long so I am a little puzzled by this.
EDIT
At the moment the sprite is moving to the right of the screen, as needed:
if(spriteTimer>delay)
{
invadersSprite.setTextureRect(area);
++count;
invadersSprite.move(right,0);
if(count==SPRITECOLS) //WE HAVE MOVED OFF THE RIGHT OF THE IMAGE
{
area.left=0; //reset texture rect at left
count=0; //reset count
}
else
{
area.left+=spaceWidth; //move texture rect right
}
spriteTimer=0; //we have made one move in the sprite tile - start timing for the next move
}
Your current logic will only move the sprite left once if the x-coord is greater than 650 - but that's not exactly what you want. What you want is for the sprite to continuously move left after reaching the edge.
To do this you'll need to keep track of a current velocity for your sprite. For example, when your sprite starts, it will be moving right:
xVelocity = right;
Then you can have 2 conditions that will switch direction (when hitting edges of screen):
if (invaderSprite.getPosition().x >= screenWidth) {
// hit the right side of screen
xVelocity = left;
} else if (invaderSprite.getPosition().x <= 0) {
// hit the left side of screen
xVelocity = right;
}
Now, on ever game tick, you simply move your sprite according to its current velocity:
invaderSprite.move(xVelocity, yVelocity);
There are some other things that will need to be fixed, like taking the width of the sprite into consideration, changing the y velocity, etc., but this is the main idea.