# "Squeezing" a game object based on distance to another game object [duplicate]

I am trying to "squeeze" a gameObject. When distance starts to be 6.98, execute this code: "The smaller the distance between gameObject1 and gameObject2, the thinner and longer this gameObject is". Somehow, this code has no effect. Why?

public Transform gameObject1;
public Transform gameObject2;

void Update ()
{
float distance_squeeze = Vector3.Distance(gameObject1.position,
gameObject2.position);
if(distance_squeeze < 6.98F)
{
transform.localScale = new Vector3(-distance_squeeze, distance_squeeze, 1);
}
}
• Which object is this script attached to? Oct 26, 2015 at 6:47
• The object that will be "squeezed". Oct 26, 2015 at 6:59
• Does this object have a parent? If not, use transform.scale.x or something similar. Oct 26, 2015 at 7:15
• Yes, my object has a parent. Oct 26, 2015 at 7:24
• If your code doesn't to anything (eg. no scaling at all), then you should probably try to debug it? Is your if condition met at all? Oct 26, 2015 at 8:31

If I understand question correctly, you wish to reduce width(x scale) so that total area of object is maintained. In order to do that, when setting x scale you need to set y scale to 1/x.
Second part is finding the x scale. Please note that it is relative to object width:

float original_width = 6.98f; //no magic constants, this will pay off in long run
void Update ()
{
float distance_squeeze = Vector3.Distance(gameObject1.position, gameObject2.position);
//note: you probably wanted to subtract gameObject2's witdth/2 here - you probably wanted distance from edge, not center
float scale_x = distance_squeeze / original_width; //relative
scale_x = Mathf.Min(scale_x, 1.0f); //do no stretch, equivalent to if(<6.98f)
transform.localScale = new Vector3(scale_x, 1.0f / scale_x, 1.0f);
}

note: this assumes default scale 1.0f, for details see chat linked in comments.

• Comments are not for extended discussion; this conversation has been moved to chat.
– user1430
Oct 26, 2015 at 15:13
• Hello again! I have a question regarding your code: How can I adjust the speed of the "squeeze"? (+1) Dec 19, 2015 at 17:09