C# rookie here. Familiar with some coding basics, and it feels like something should exist to help fix this, but I’m not sure what.
I have a function that I use to move a square cursor around a square grid (modelPosition):
public Vector2 pressAndHoldMoveUp(Vector2 MODELPOSITION)
{
Vector2 modelPosition = MODELPOSITION;
float counterHoldLimit = 0.5f;
//float keyCooldown = 0f;
if (IsPressed(Keys.W))
{
//KEY Behaviour: move just once, when first pressed
if (JustPressed(Keys.W))
{
modelPosition = MoveUp(modelPosition);
keyCooldown = 0f;
}
//KEY Behaviour: If it wasn't first pressed, we need to wait--add the elapsed game time since last update call.
else
{
//keyCooldown = 0;
keyCooldown += Globals.Time;
}
//KEY Behaviour: if we've waited long enough (passed the counterHoldLimit), it will move the position once, and then reset keyCooldown to 1/3.5th the counterHoldLimit
if (keyCooldown > counterHoldLimit)
{
modelPosition = MoveUp(MODELPOSITION);
keyCooldown = keyCooldown - (counterHoldLimit / 3.5f);
}
}
return modelPosition;
}
public Vector2 pressAndHoldMoveDown(Vector2 MODELPOSITION)
{
Vector2 modelPosition = MODELPOSITION;
float counterHoldLimit = 0.5f;
//float keyCooldown = 0f;
if (IsPressed(Keys.S))
{
//KEY Behaviour: move just once, when first pressed
if (JustPressed(Keys.S))
{
modelPosition = MoveDown(modelPosition);
keyCooldown = 0f;
}
//KEY Behaviour: If it wasn't first pressed, we need to wait--add the elapsed game time since last update call.
else
{
//keyCooldown = 0;
keyCooldown += Globals.Time;
}
//KEY Behaviour: if we've waited long enough (passed the counterHoldLimit), it will move the position once, and then reset keyCooldown to 1/3.5th the counterHoldLimit
if (keyCooldown > counterHoldLimit)
{
modelPosition = MoveDown(MODELPOSITION);
keyCooldown = keyCooldown - (counterHoldLimit / 3.5f);
}
}
return modelPosition;
}
The only difference is that one uses the W key to move up while the other uses the S key to move down. It feels like there should be a way to simplify to use only one function where I pass in the direction (up/down) and the respective key. However, I’m not sure how I could pass in a function and key.
Any ideas? Thanks for help.