2
\$\begingroup\$

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);
    }   
}
\$\endgroup\$
8
  • \$\begingroup\$ Which object is this script attached to? \$\endgroup\$ – SanSolo Oct 26 '15 at 6:47
  • \$\begingroup\$ The object that will be "squeezed". \$\endgroup\$ – That's me. Oct 26 '15 at 6:59
  • \$\begingroup\$ Does this object have a parent? If not, use transform.scale.x or something similar. \$\endgroup\$ – SanSolo Oct 26 '15 at 7:15
  • \$\begingroup\$ Yes, my object has a parent. \$\endgroup\$ – That's me. Oct 26 '15 at 7:24
  • 1
    \$\begingroup\$ 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? \$\endgroup\$ – bummzack Oct 26 '15 at 8:31
2
\$\begingroup\$

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.

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.