1
\$\begingroup\$

I am using Turbo C++ to make a game using the graphics.h library (I know it's a bit old). In this game, the player can move left, right and they can jump using A, D and W (just like in Super Mario).

I am using the kbhit() function to get inputs from user. The problem with it is that I cannot jump and move the character at the same time (so it moves in a parabolic trajectory). How can I take multiple inputs so that, for example, if I press W and D, character will jump towards right?

The code is given below:

if(kbhit())
{
    ch=getch();

    if(ch=='e'){break;}   //exit

    if(ch=='d')           //move right
    {
    ax=1;
    if(vx<vellim){vx=vx+ax*dt;}
    dx=vx*dt;
    x+=dx;
    s_mario(x,y); //This function draws the character at the appropriate place

    }

    if(ch=='a')             //move left
    {
    ax=-1;
    if(vx>-vellim){vx=vx+ax*dt;}
    dx=vx*dt;
    x+=dx;
    s_mario(x,y);
    }

    if(ch=='w'&&jumpkey==0)   //jump
    {
    vy=60;
    jumpkey=1;
    }

}

if(jumpkey==1)
{
vy=vy-g;
dy=vy*dt;
y-=dy*0.1;
if(y>400){y=399;vy=0;jumpkey=0;}
s_mario(x,y);

}

if(!kbhit())
{       vx*=c;
    dx=vx*dt;
    x+=dx;
    s_mario(x,y);
    delay(5);
}
\$\endgroup\$
  • \$\begingroup\$ Unfortunately getch() is used for key presses, but what you want is separate key down and key up events (or as KevLoughrey says, a function that tells you the key state). See more discussion on stackoverflow with sample code. \$\endgroup\$ – amitp Sep 16 '18 at 15:20
1
\$\begingroup\$

Console I/O wasn't designed for this kind of thing. You'll need a different means of handling input.

Google suggests that the GetAsyncKeyState() is what you're looking for:

Documentation: https://msdn.microsoft.com/en-us/library/windows/desktop/ms646293(v=vs.85).aspx

Example usage: http://www.cplusplus.com/forum/beginner/135868/#msg725863

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.