Basically I want to move my enemy from one position to another.
There starting position is not a problem... neither is the place where they are suppose to go.
The problem lies with the how they get there. With the code I wrote they just teleport off the map.
So I am not even going to post it. Using triangles... what would be the most efficient way to get them from point A to point B?
Lets say point A is 10, 10; and point B is 123, 349. But there is also the chance that A will be B and B will be A. So it also has to deal with negati开发者_开发知识库ves.
Now the last thing that complicates the matter is that it moves between 1 and 5 pixels every time it repaints... so if it goes over the position I am not sure how to check to see if its in the general area.
Thanks! Btw I don't need full code... just IDEAS!!! I can code myself. Thank you!!!
current code:
if (enemyList.length > 0) {
for (int[] x : enemyList) {
double changeX;
double changeY;
//if already in spot, anounce it
if (x[0] == x[2] && x[1] == x[3]) {
x[2] = -1;
x[3] = -1;
}
//if anounced generate new spot of interest
if (x[2] == -1 || x[3] == -1) {
x[2] = generateRandom(0, 550);
x[3] = generateRandom(0, 400);
}
//find distance from target and move there
int _y = x[1] - x[3];
int _x = x[0] - x[2];
if (_x > _y) {
changeX = _x / _y;
changeY = _y / _y;
} else {
changeY = _y / _x;
changeX = _x / _x;
}
changeY = changeY * generateRandom(0, 10);
changeX = changeX * generateRandom(0, 10);
//change physical position
x[0] += (int) changeX;
x[1] += (int) changeY;
}
}
Based on the code it looks like your enemy will sort of wiggle to its destination in maybe a curved fashion, but it's hard to tell just by inspection. Maybe you just need to swap your source and destination because it looks like you may just have it backwards:
int _y = x[3] - x[1];
int _x = x[2] - x[0];
Is this what you intended, or should it make a beeline?
speed = 5; // "pixels" per frame
deltaX = destX - sourceX;
deltaY = destY - sourceY;
distance = sqrt(deltaX^2 + deltaY^2);
moveX = speed / distance * deltaX;
moveY = speed / distance * deltaY;
newX = sourceX + moveX;
newY = sourceY + moveY;
I used similar triangles to calculate moveX
and moveY
. Note the square root is slow, but that may be ok for your purposes... once you have it working, there are ways to optimize out the square root.
精彩评论