I want my character to move continuously while the arrow key is pressed, but currently, I press a key, he moves an interval, and I have to press the key again before he will move again. Here is my current code:
if (IsKeyPressed(eKeyUpArrow) == 1)
cglitch.Walk(cglitch.x, cglitch.y-10);
if (IsKeyPressed(eKeyDownArrow) == 1)
cglitch.Walk(cglitch.x, cglitch.y+10);
if (IsKeyPressed(eKeyRightArrow) == 1)
cglitch.Walk(cglitch.x+10, cglitch.y);
if (IsKeyPressed(eKeyLeftArrow) == 1)
cglitch.Walk(cglitch.x-10, cglitch.y);
The KeyboardMovement Module included in the default game template already does that. All you need is, call
KeyboardMovement.SetMode(eKeyboardMovement_Pressing);
when the game starts.
Even if you don't want to use this Module, you may still check its codes and learn from them.
Ok, thanks! But, how do I do that?
If you started making the game by selecting the default template, you are already using it.
If not, start another (dummy) game by choosing the default template and then click Scripts, right click on KeyboardMovement_102.asc and export the module to a file. You can then re-import this module into your game.
It's working now!
Thank you!
I realize you have this working now but if you or someone wanted to make your own instead of using that default script, I believe this works without issues:
Variables at the top of the Global Script (outside of a function)
bool keyboardMovement;
int keyboardMovementDirection;
Inside repeatedly execute in the Global Script
if (!IsGamePaused() && IsInterfaceEnabled() && player.on)
{
bool dUp, dRight, dDown, dLeft;
int newDirection;
if (IsKeyPressed(eKeyUpArrow)) dUp=true;
if (IsKeyPressed(eKeyRightArrow)) dRight=true;
if (IsKeyPressed(eKeyDownArrow)) dDown=true;
if (IsKeyPressed(eKeyLeftArrow)) dLeft=true;
if (dUp && dRight) newDirection=2;
else if (dRight && dDown) newDirection=4;
else if (dDown && dLeft) newDirection=6;
else if (dLeft && dUp) newDirection=8;
else if (dUp) newDirection=1;
else if (dRight) newDirection=3;
else if (dDown) newDirection=5;
else if (dLeft) newDirection=7;
else newDirection=0; //nothing
if (newDirection!=keyboardMovementDirection)
{
keyboardMovement=true;
int newX, newY;
if (newDirection==1 || newDirection==2 || newDirection==8) newY=-1000;
else if (newDirection==4 || newDirection==5 || newDirection==6) newY=1000;
if (newDirection==2 || newDirection==3 || newDirection==4) newX=1000;
else if (newDirection==6 || newDirection==7 || newDirection==8) newX=-1000;
player.WalkStraight(player.x+newX, player.y+newY, eNoBlock);
keyboardMovementDirection=newDirection;
}
else if (newDirection==0 && keyboardMovement)
{
keyboardMovement=false;
player.StopMoving();
}
}