Monday, March 5, 2018

tower defense - How to calculate the enemy to arrive in the middle of cell?


The game is 2d, and the genre of this game is tower defense.


I managed to get it moving to the cell and arrived in the cell. But it never arrives at the middle of a cell.


Here's what I did...


public Enemy plotPath(Cell start, Enemy enemy, float deltaTime) {

//Direction

int directionx = 0;
int directiony = 0;
if(enemy.position.x < start.position.x) {
directionx = GraphConstants.X_DIRECTION_RIGHT;
}
else if(enemy.position.x > position.x){
directionx = GraphConstants.X_DIRECTION_LEFT;
}
else {
directionx = GraphConstants.X_DIRECTION_NA;

}

if(enemy.position.y < start.position.y) {
directiony = GraphConstants.Y_DIRECTION_DOWN;
}
else if(enemy.position.y > start.position.y){
directiony = GraphConstants.Y_DIRECTION_UP;
}
else {
directiony = GraphConstants.Y_DIRECTION_NA;

}
enemy.position.add(velocity.x * deltaTime * directionx, velocity.y * deltaTime * directiony);

return enemy;
}

Then, the game would calculate the distance between the enemy and a point. If it is zero, then remove the cell from the enemy's list of cells (A*star algorithm). The enemy position would be calculated by vector addition. It looks like the enemy's position wouldn't never arrive at the point.


Vector addition


public Vector2 add(float x, float y) {
this.x += x;

this.y += y;
return this;
}

I have the enemy positioned in (-0.1f, 3.5f). The velocity of the enemy is 2f. The cell is based 1f x 1f. The middle of a cell is (0.5f, 3.5f);


I logged the calculations, here's the calculations -


-0.1    3.5
0.03482666 3.5
0.04385986 3.5
0.054541014 3.5

0.072546385 3.5
0.106665045 3.5
0.14072266 3.5
0.17520753 3.5
0.21030274 3.5
0.24313965 3.5
0.27927247 3.5
0.31210938 3.5
0.3467163 3.5
0.3805298 3.5

0.41867676 3.5
0.44882813 3.5
0.486792 3.5
0.5188354 3.5

I used distance between the enemy and the middle of a cell -


if(position.dist(start.position) == 0) {
path.remove(0);
}


I'm thinking the velocity * deltaTime * direction isn't correct. I tried to google around but couldn't find the solution. Any ideas?



Answer



Can you show the code where you check if it has arrived? Do you make a floating point comparison using == ? That would not work, check for >= or <=


Edit: You are right, velocity * deltaTime * direction isn't correct, because the velocity should already be the direction, assuming that the velocity has been set properly. It should only be velocity * deltaTime, but I dont think thats the problem, since it actually arrived as your logging shows.


Edit: Instead of:


if(position.dist(start.position) == 0)

use something like:


if(position.dist(start.position) < 0.3)

No comments:

Post a Comment

Simple past, Present perfect Past perfect

Can you tell me which form of the following sentences is the correct one please? Imagine two friends discussing the gym... I was in a good s...