Yeah I was thinking collisions could be an issue but it should mostly work. But yeah the velocity bit is probably problematic. You could also cancel the part of the velocity of the objects moving away from each other.
Here’s one way to do that. You’d do this in addition to correcting the position in my other post. Relv is the velocity of the objects moving toward or away from each other. Then you’d subtract that from the velocity’s so it just keeps the rest of the velocity.
Ang=angle(a.x,a.y,b.x,b.y)
Relv= (a.vx-b.vx)*cos(ang)+(a.vy-b.vy)*sin(ang)
A: set vx to a.vx-relv*cos(ang)
A: set vy to a.vy-relv*sin(ang)
… same for b
Overall setting the position is nice in that it provides a hard limit to how far objects can move apart. Adding a velocity correction to that helps.
Just changing the velocity to limit the positions indirectly is another idea for sure. It’s actually what the physics behavior does to resolve collisions and joints. In practice it can be a bit spongier though. A quick way is to apply an acceleration to the objects toward each other if too far apart which is a bit spongy. Another idea is to just do the velocity correction above. Probably only if the relv>0 or moving apart. However you’ll still need to add a bit more velocity to move the objects back toward each other otherwise they will drift apart