Do you want the red sticky actor to stick only to the one gray actor? Or is the sticky actor supposed to stick to many different actors as well? If you just want it to stick to a single gray actor at a time, what you need to do is store a reference to the gray actor you want it to stick to. From there you can prevent the sticky one from ever going beyond a certain distance away from the gray one.
- Code: Select all
// this assumes there is only one gray actor for simplicity
int radius = (width + height) / 4; // using an average of height and width for simplicity
int gray_radius = (gray.width + gray.height) / 4;
int max_dist = radius + gray_radius;
if(distance(x, y, gray.x, gray.y) > max_dist))
{
float ang = direction(gray.x, gray.y, x, y);
x = gray.x + cos(ang)*max_dist;
y = gray.y - sin(ang)*max_dist;
}
This is just the idea presented in a simplified form. Since you are dealing with squares you should probably set x and y independently and not use radius. Also the above example would only work with one gray actor, so you would need to use some way of tracking which gray actor a given sticky one is connected to.