I'm trying to put together a struct or a method of some sort that will allow me to check the relative position between two objects, and if they're too far apart, apply a force that will draw them closer to eachother. I've read that you can achieve this by creating a 'spring', what that might look like in code?
None-physical way (not spring physics):
If I simply wanted an object to pull towards another object and stop there I would use this instead:
Define too far apart as a radius
Lets say the attractor is
This would attract an object to another without 'letting go' once it gets there.
To simulate spring physics in one direction, use this:
k is a coefficient and x is the distance between the objects.
F will determine the acceleration speed between object A(attractor) and object B(attracted).
Like dreta mentioned, you could use
Which is basically : (I am taking deltaT, frame time in seconds into account)
Otherwise do something like:
To simulate the foce, check for the angle between them:
The new velocity for B will be:
This is not classic spring behavior as it does not consider the fact that the spring will repel an object if it is too close (closer than the equilibrium point).
If you wish to emulate that, detract a constant
|show 7 more comments|
What you need to implement is Hookes law. This is an equation which calculates the force created by a spring. The equation is;
where x is the how far a way the spring is from its 'natural' or resting length. i.e if a spring has a resting length of 5 meters and is stretched to 8 meters, x is 3 in this case. k is the spring constant, which controls how 'strong' the spring is. Note there is a minus sign. That is because the force acts in the opposite direction of the direction of stretching (or compression).
Once you know F, you can calculate the acceleration a=F/mass.
you will probably want to include damping in your model, otherwise an will bounce back and forth forever.
Now your equation will be
v is the velocity of the object and c is the amount of damping (bigger values mean the oscillation will stop sooner
Rather than invoking physics, simpler solution would be to constantly adjust their positions to make sure that they are the required distance apart.
In this code adjust the 0.01 value to make the objects move quicker or slower.