I'm making a RPG with libGDX. I've loaded a TiledMap and now I'm implementing the player movement. The view is top-down.
In my game I want two ways of input: one is using the ARROW keys to move the player. This implementation works pretty well, including collisions. The second one is a movement based in the mouse. When I click, then the player starts to follow the mouse pointer
private void autoMove(float speed)
{
//Start or stop moving
if (Gdx.input.justTouched())
{
autoMoving = !autoMoving;
}
//Start follow the mouse
if (autoMoving)
{
//Get direction
Vector3 point = this.getStage().getViewport().getCamera().unproject(new Vector3(Gdx.input.getX(),Gdx.input.getY(),0));
dir = new Vector2(point.x - pos.x, point.y- pos.y);
//Normalize
dir.nor();
//Set correct animation
if (Math.abs(dir.x) <= 0.5)
{
if (dir.y >= 0)
{
lookingDirection = UP;
}
else
{
lookingDirection = DOWN;
}
}
else
{
if (dir.x >= 0)
{
lookingDirection = RIGHT;
}
else
{
lookingDirection = LEFT;
}
}
//Scale to speed and move
dir.scl(speed);
pos.add(dir);
}
As you can see, I use global variable dir
to store the direction of the player. Now I want to handle the collisions with this input. However, I'm not able to do this. I've tried, for example, using pos.add(dir.scl(-1.0f))
but doing this the player gets blocked in every direction. After that, I tried to make the same but blocking only x or y movement based on the lookingDirecion
variable. However, player can be looking at right and move a bit upwards, to it's possible to "hack" the system and introduce the player inside the block. I tried with more complex if structures but they didn't worked at all.
The collision code looks like this, if it's useful.
public void checkBounds(float speed)
{
for (int i=0; i < map.getWidthInTiles(); i++)
{
for (int j=0; j < map.getHeightInTiles(); j++)
{
//bound is player's rectangle. colBounds are map's impenetrable objects.
if (bound.overlaps(map.colBounds[i][j]))
{
if (!autoMoving) //Control with ARROW keys
{
if (lookingDirection == UP)
{
pos.y -= speed;
}
else if (lookingDirection == DOWN)
{
pos.y += speed;
}
else if (lookingDirection == RIGHT)
{
pos.x -= speed;
}
else if (lookingDirection == LEFT)
{
pos.x += speed;
}
}
else
{
//MOUSE COLLISION DETECTION
}
}
}
}
The question is: how can I implement the collision detection for this kind of movement?
Thank you!