cancel
Showing results for 
Search instead for 
Did you mean: 

Handy bit of scaling code

jpaterson
Honored Guest
I recently wrote up a bit of code to scale an object by pressing both grip triggers and bringing the controllers apart or together (similar to the zoom function on a touch screen). I figured this might be useful to a couple people out there, so here ya go!

This code also helps correct for height so as to keep the scaled object in the same location and requires min/max scale vectors to keep things from getting out of control. A pivot variable is also used (it can be assigned to the same gameObject you're scaling, or another one - can help things scale outwards from the proper location).
void Update () {
//SCALING
if (OVRInput.Get(OVRInput.Button.PrimaryHandTrigger) && OVRInput.Get(OVRInput.Button.SecondaryHandTrigger))
{
Scale();
}
}
private void Scale()
{
//Obtaining distance and velocity
Vector3 d = OVRInput.GetLocalControllerPosition(OVRInput.Controller.LTouch) - OVRInput.GetLocalControllerPosition(OVRInput.Controller.RTouch);
Vector3 v = OVRInput.GetLocalControllerVelocity(OVRInput.Controller.LTouch) - OVRInput.GetLocalControllerVelocity(OVRInput.Controller.RTouch);

//Calculating Scaling Vector
float result = Vector3.Dot(v, d);

//Adjusting result to slow scaling
float final_result = 1.0F + 0.2F * result;

Vector3 scalingFactor = Vector3.Scale(transform.localScale, new Vector3(final_result, final_result, final_result));

//Checking Scaling Bounds
if (scalingFactor.sqrMagnitude > minScale.sqrMagnitude && scalingFactor.sqrMagnitude < maxScale.sqrMagnitude)
{
Vector3 A = transform.position;
Vector3 B = pivot.transform.position;
B.y = A.y;

Vector3 startScale = transform.localScale;
Vector3 endScale = transform.localScale * final_result;

Vector3 C = A - B; // diff from object pivot to desired pivot/origin

// calc final position post-scale
Vector3 FinalPosition = (C * final_result) + B;

// finally, actually perform the scale/translation
transform.localScale = endScale;
transform.position = FinalPosition;
}
}



1 REPLY 1

jpaterson
Honored Guest
Feel free to do so. Glad you find it useful enough to add to the sticky!