Created
October 10, 2020 22:40
-
-
Save hadrizi/f14c0e5075a07d43e894ed4f8728f7cf to your computer and use it in GitHub Desktop.
Scale object so it always stand on its parent plane
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Collections; | |
using System.Collections.Generic; | |
using UnityEngine; | |
public class scale : MonoBehaviour | |
{ | |
// Scale represented as single variable | |
[Range(0.0f, 5.0f)] | |
public float objectScale = 1.0f; | |
// Scale and position represented as xyz vectors | |
private Vector3 scaleChange, positionChange; | |
// Original Y position of the object | |
private float originalY = 0.0f; | |
// Y position calculated during Update cycle | |
private float newY = 0.0f; | |
// Start function that is called once so it kepps all ORIGINAL values | |
void Start() | |
{ | |
// Here we save our original y position and never change it further | |
originalY = transform.localPosition.y; | |
} | |
// Update is called once per frame | |
// I use localPosition, it means that I move my object relative to parent plane | |
// if object is not child of any parent, then our target plane is XZ plane | |
void Update() | |
{ | |
/* | |
* This is where all magic happens. | |
* So we need to keep our object stnading on the parent plane(globally XZ plane) | |
* First of all we need to understand how our original y relates to our original scale: | |
* well, it is simply originalY/1. | |
* Consequently, we get ourself a proportion | |
* !!! Y/objectScale = originalY/1 !!! | |
* From that we need to get Y, it equals (objectScale * originalY) / 1 (we can drop division by one) | |
*/ | |
newY = objectScale * originalY; | |
positionChange = new Vector3(transform.localPosition.x, newY, transform.localPosition.z); | |
// Set our new position | |
transform.localPosition = positionChange; | |
// Change scale | |
scaleChange = new Vector3(objectScale, objectScale, objectScale); | |
transform.localScale = scaleChange; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment