Take the 2-minute tour ×
Game Development Stack Exchange is a question and answer site for professional and independent game developers. It's 100% free, no registration required.

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

share|improve this question

closed as not a real question by Anko, Byte56, bummzack, Josh Petrie, msell Apr 25 '13 at 8:57

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.If this question can be reworded to fit the rules in the help center, please edit the question.

3  
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

1 Answer 1

up vote 1 down vote accepted

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;
share|improve this answer
    
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

Not the answer you're looking for? Browse other questions tagged or ask your own question.