Move Gameobject towards/away from position based on the proximity of 2 other objects
OK, so I have 4 cubes in a scene. I'm trying to achieve the following:
Player moves cubeA towards cubeB.
At a specific proximity of cubeA to cubeB, move cubeC towards cubeD.
If the player moves cubeA away from cubeB, cubeC returns back to it's original position.
The proximity of cubeA to cubeB can be reached in any vector3 position. However, cubeC and cubeD should only move towards/away from each other along the same axis.
So far, I'm using MoveTowards for the first part.
public Transform CubeB;
public float proximity = 5.0F;
bool ProximityReached;
public Transform CubeC;
public Transform CubeD;
private float AdaptsqrLen;
void Update() {
Vector3 offset = CubeB.position - transform.position;
float sqrLen = offset.sqrMagnitude;
if (sqrLen < proximity * proximity){
ProximityReached = false;
}
else {
ProximityReached = true;
}
AdaptsqrLen = sqrLen -5;
CubeC.transform.position = Vector3.MoveTowards(CubeD.position, CubeC.transform.position, AdaptsqrLen);
}
This method works for the first part, without adapting sqrLen. However, when I subtract from the sqrLen to let MoveTowards returns negative values, CubeC position flickers between two positions on the same axis, either side of CubeD - probably because I'm not declaring what direction to move it away in.
Any thoughts how I can adapt this to achieve the objective?
Thanks!