Your question is quite confusing, but I think I understand what you’re after. If I understand correctly, as the red cube moves, you want the other cube to stretch to maintain the visual connection. Anyhow, first off, you shouldn’t name a variable object public Transform object;. Your code editor should give you an error saying it is an invalid token because it is reserved type for System.Object in C#, but I think you meant to have public Transform player; there.
The distance is being calculated without taking the cube scale into mind which is ok if the cube Vector3(1,1,1) scale (or at least the z scale) is equivalent to a single unit, but assumptions like that are not very future proof. So to future proof it, we can do the following to distance:
var localizedPlayerPosition = transform.parent.worldToLocalMatrix.MultiplyPoint3x4(player.position);
float distance = localizedPlayerPosition.z;
Now your scaleFactor is really small. We need to make sure the the cube z expands properly and for that, we just need to change the scaleFactor value to 2.0f. This is because when you are scaling, the scale is affecting both sides of the origin on each axis. So if there is a distance of 1 and you set a scale of 1, each side will be offset from the origin by 0.5. So we need to multiply the distance by 2 to compensate to get 1 on each side of the origin. BUT it seems odd to have the other side get bigger as well, so I assume that is not wanted…
If you don’t want the other side to get bigger at the same time and you just want the side that attaches to the red cube to be dynamic (which feels more natural and I think it’s probably what you’re after), you have to change position and scale and just get rid of the scaleFactor multiplication all together.
Here is what I think you want:
public class CubeScaler : MonoBehaviour {
public Transform player;
private Vector3 initialScale;
private Vector3 initialPosition;
private void Start()
{
initialScale = transform.localScale;
initialPosition = transform.localPosition;
}
private void Update()
{
var localizedPlayerPosition = transform.parent.worldToLocalMatrix.MultiplyPoint3x4(player.position);
float distance = localizedPlayerPosition.z;
transform.localScale = new Vector3(initialScale.x, initialScale.y, distance);
transform.localPosition = new Vector3(initialPosition.x, initialPosition.y, (distance - initialPosition.z) * 0.5f);
}
}
I tested it quick and here is the result:
