- Home /
Game Object Scaling based on Proximity
helloHello,
I want to scale a Game object based on how far away on how close the player is.
Note This is eventually for VR. I have a Game Object thats a small room and as you get closer it scales to be larger & visVersa.
What am I doing wrong?
public class scalePlayer : MonoBehaviour
{
public GameObject room;
public Transform center;
public float oldDist;
void Awake()
{
//Determine the Starting Distance between player and center of room to be scaled
float oldDist = Vector3.Distance(center.position, transform.position);
}
void Update()
{
//Determine the New distance between player and center of room to be scaled
float newDist = Vector3.Distance(center.position, transform.position);
room.transform.localScale = room.transform.localScale * (oldDist - newDist) * Time.deltaTime;;
}
}
There has to be an elegant way to do this
The scale of the room just goes down to Zero
Any ideas?
Thanks!
~be
Answer by Hellium · Dec 13, 2020 at 07:50 PM
You were on the right track actually. Lenda0210 is right indicating you should remove the Time.deltaTime. If you want to scale down the closer the object is from the center (if the obejct is at center's position, the object will have a scale of (0,0,0):
public class scalePlayer : MonoBehaviour
{
public GameObject room;
public Transform center;
public float ScaleMultiplier;
private Vector3 initialScale;
void Awake()
{
initialScale = room.transform.localScale;
}
void Update()
{
float distance = Vector3.Distance(center.position, transform.position);
room.transform.localScale = initialScale * distance * ScaleMultiplier;
}
}
If you want the room to have its initial size when the object is on the same position as the center:
void Update()
{
float distance = Vector3.Distance(center.position, transform.position);
room.transform.localScale = initialScale + Vector3.one * distance * ScaleMultiplier;
}
@Hellium Awesome! Thank you ! Since I want make the Object Larger as you approach I modded the code like such:
public class scalePlayer : $$anonymous$$onoBehaviour
{
public GameObject room;
public Transform center;
public float Scale$$anonymous$$ultiplier;
private Vector3 initialScale;
void Awake()
{
initialScale = room.transform.localScale;
}
void Update()
{
float distance = Vector3.Distance(center.position, transform.position);
room.transform.localScale = (initialScale / distance) * Scale$$anonymous$$ultiplier;
}
}
Thanks both @Lenda0210 & @Hellium
Your answer
Follow this Question
Related Questions
Can the insides of a gameObject affect its transform? 0 Answers
GameObject Scale as World Coordinates (Units)? 1 Answer
How do I permanently resize a model with children? 2 Answers
True scale of a visible GameObject with many childs 1 Answer
Keeping textures unstretched even as a gameobject scale is changed 1 Answer