Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Scaling a mesh using a pivot

Discussion in 'Scripting' started by Mehd, Jul 9, 2018.

  1. Mehd

    Mehd

    Joined:
    Apr 29, 2016
    Posts:
    91
    Hello,

    I'm trying to scale a mesh along a custom axis, defined globally. I wrote a test script but it doesn't work the way I want. One of the reasons is that the mesh is scaled with the pivot point located at the center. Is there any way to change that ?

    Here's my code so far:

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class SphereExtend : MonoBehaviour {
    6.     public Transform target;
    7.     public Transform Ini;
    8.     public float MaxMagni ;
    9.     public float Speed;
    10.  
    11.  
    12.     Vector3 axis;
    13.     // Use this for initialization
    14.     void Start () {
    15.  
    16.         axis = target.position - Ini.position;
    17.     }
    18.    
    19.     // Update is called once per frame
    20.     void Update () {
    21.  
    22.         Vector3 new_scale = transform.localScale;
    23.         new_scale = Vector3.Lerp(new_scale, (new_scale + axis.normalized), Speed*Time.deltaTime);
    24.         new_scale = Vector3.ClampMagnitude(new_scale, MaxMagni);
    25.  
    26.         transform.localScale = new_scale;
    27.         // transform.position += axis.normalized*Speed*Time.deltaTime;
    28.  
    29.  
    30.        
    31.     }
    32. }
    Thanks a lot !
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,514
    By the way the meshes within a GameObject are defined, they live in local space, which means they are mathematically around (0,0,0), their implicit pivot.

    You can handle by first subtracting the pivot you want, then doing the scaling, then adding back in the pivot you want

    Write some numbers on a page to sorta see what I mean in a single dimensions:

    -2, 0, 1

    If you just scale it by 2, you get:

    -4, 0, 2

    That "pivots" around 0.

    Lets say you actually wanted it to pivot around the -2 (ie., the -2 stays the same).

    original numbers: -2, 0, 1

    subtract the pivot (-2):

    -2 - (-2), 0 - (-2), 1 - (-2)

    which gives you: 0, 2, 3 (remember minus of a minus is a plus)

    Now scale it by 2:

    0, 4, 6

    Now add back in the original pivot (-2):

    -2, 2, 4

    Voila! Those are the original numbers scaled by 2, but done so around the -2 point.

    Same goes if you want to rotate numbers around a custom pivot: remove the pivot first, rotate the numbers, then add the pivot back.
     
    Mehd likes this.