# How do I detect when one sprite is moving away from another? [closed]

I'm currently working with crafty.js. I need to know how to detect when one sprite is moving away from another sprite.

• You need to give us a lot more detail about your problem. For starters, are the sprites in question under the control of the player or your movement code? In other words, can you simply check "if movementVector1 dot movementVector2 < 0" or is your situation more complicated than that? – jhocking Apr 21 '13 at 16:22

So I'm assuming you have an X/Y coordinate for each sprite, and some kind of loop that executes in your game. Given that, just calculate the distance between the two sprites each cycle in the loop. Compare the current distance from the distance in the previous loop, and if it is more, they are moving apart.

Something like this...

float old_distance = 0.0;
float current_distance = 0.0;

sprite A;
sprite B;

loop() {
old_distance = current_distance;
current_distance= sqrt((A.x-B.x)^2 + (A.y-B.y)^2);
if (current_distance > old_distance) {
// --- They are moving away from each other
}
}


I believe you could just not do the square root calculation, as you really don't care about the exact distance, just whether one is farther away than the other. So just...

current_distance= (A.x-B.x)^2 + (A.y-B.y)^2;

• I was looking for a solution specific to crafty.js but I guess I'll have to use this. – gnerkus Apr 22 '13 at 13:41
• This is pretty much how you'd do it in any platform. Maybe crafty.js has a shortcut function to calculate distance, to help - but this is basically what one would do. You don't need any fancy vector math or anything complicated. – Tim Holt Apr 22 '13 at 16:01