Adventure Game Studio

AGS Support => Beginners' Technical Questions => Topic started by: brushfe on Mon 30/12/2024 15:30:54

Title: [SOLVED] Keyboard movement script question(s)
Post by: brushfe on Mon 30/12/2024 15:30:54
func repeatedly_execute()
{
// Direct position changes based on keyboard input
if (IsKeyPressed(eKeyUpArrow)) cEgo.y -= 2;
if (IsKeyPressed(eKeyDownArrow)) cEgo.y += 2;
if (IsKeyPressed(eKeyLeftArrow)) cEgo.x -= 2;
if (IsKeyPressed(eKeyRightArrow)) cEgo.x += 2;

}

And running these commands at the start of the game:

// Adjusting this changed the rate of position change
SetGameSpeed(30)

// Set Ego to first view
cEgo.LockView(1);
cEgo.Animate(0, 16, eRepeat, eNoBlock, eForwards);
[/list]
Title: Re: [SOLVED] Keyboard movement script question(s)
Post by: Khris on Wed 01/01/2025 12:49:27
Right; I misread the original post and was wondering about the weird requirements but it does make sense now.
Your solution is correct; you need to completely skip the built-in walking.

Minor rewrite suggestion:
function repeatedly_execute()
{
  int speed = 2;
  // Direct position changes based on keyboard input
  cEgo.x += (IsKeyPressed(eKeyRightArrow) - IsKeyPressed(eKeyLeftArrow)) * speed;
  cEgo.y += (IsKeyPressed(eKeyDownArrow) - IsKeyPressed(eKeyUpArrow)) * speed;
}

Btw, this implementation means the character will move ~ 1.5x faster when moving diagonally.
This can be fixed by using floats for the position:

float egox, egoy;
function repeatedly_execute()
{
  float speed = 2.2;
  // Direct position changes based on keyboard input
  float dx = IntToFloat(IsKeyPressed(eKeyRightArrow) - IsKeyPressed(eKeyLeftArrow));
  float dy = IntToFloat(IsKeyPressed(eKeyDownArrow) - IsKeyPressed(eKeyUpArrow));
  if (dx != 0.0 && dy != 0.0) speed *= 0.7071;
  egox += dx * speed;
  egoy += dy * speed;
  cEgo.x = FloatToInt(egox, eRoundNearest);
  cEgo.y = FloatToInt(egoy, eRoundNearest);
}
Title: Re: [SOLVED] Keyboard movement script question(s)
Post by: brushfe on Fri 10/01/2025 19:46:30
@Khris Sorry I missed your reply!

This is fantastic and much more precise and elegant. And the solution to diagonal movement is very kind of you to include. Thanks so much!