I am developing a "game engine" (with Processing's core.jar as a library) to use for a future game, and have got some basic structure setup, however I have tried testing creating a moving player and realized that the movement handling I have created is embarrassing and it also doesn't function perfectly. For example, the diagonal speed is just a guess, and the whole thing is just feels unnecessarily bloated.
@Override
public void update(Entity entity, double delta)
{
if (movingLeft && movingUp && movingRight)
{
entity.setY((entity.getY() - 3.0f) * (float) delta);
}
else if (movingUp && movingRight && movingDown)
{
entity.setX((entity.getX() + 3.0f) * (float) delta);
}
else if (movingRight && movingDown && movingLeft)
{
entity.setY((entity.getY() + 3.0f) * (float) delta);
}
else if (movingDown && movingLeft && movingUp)
{
entity.setX((entity.getX() - 3.0f) * (float) delta);
}
else if (movingUp && movingRight)
{
entity.setX((entity.getX() + 2.0f) * (float) delta);
entity.setY((entity.getY() - 2.0f) * (float) delta);
}
else if (movingRight && movingDown)
{
entity.setX((entity.getX() + 2.0f) * (float) delta);
entity.setY((entity.getY() + 2.0f) * (float) delta);
}
else if (movingDown && movingLeft)
{
entity.setX((entity.getX() - 2.0f) * (float) delta);
entity.setY((entity.getY() + 2.0f) * (float) delta);
}
else if (movingLeft && movingUp)
{
entity.setX((entity.getX() - 2.0f) * (float) delta);
entity.setY((entity.getY() - 2.0f) * (float) delta);
}
else if (movingUp)
{
entity.setY((entity.getY() - 3.0f) * (float) delta);
}
else if (movingRight)
{
entity.setX((entity.getX() + 3.0f) * (float) delta);
}
else if (movingDown)
{
entity.setY((entity.getY() + 3.0f) * (float) delta);
}
else if (movingLeft)
{
entity.setX((entity.getX() - 3.0f) * (float) delta);
}
}
How could I optimize this? It would be useful if I knew how to create a better movement system for the future when I do create a game, especially since I already have an idea in mind and want to start working with this engine as soon as it is "usable enough" to start my game.
How about creating 2 direction variables for X and Y?
public void update(Entity entity, double delta) {
int directionX = 0;
int directionY = 0;
if (movingLeft) directionX -= 1;
if (movingRight) directionX += 1;
if (movingUp) directionY -= 1;
if (movingDown) directionY += 1;
if (directionX != 0 && directionY != 0) {
// move in both direction
entity.setX((entity.getX() + 2.0f * directionX) * (float) delta);
entity.setY((entity.getY() + 2.0f * directionY) * (float) delta);
return;
}
// move in one direction or not moving
entity.setY((entity.getY() + 3.0f * directionY) * (float) delta);
entity.setX((entity.getX() + 3.0f * directionX) * (float) delta);
}