- Home /
Changing size of a 2d object
I have a 2d rectangle. It will be 10 units long in the beginning, then it will be scaled to x percent of the 10 units, then 10 units again. But it wont directly change size, we will see it getting longer and shorter. When i tap it will stay at the size it is when tapping happens.
I have written and deleted code many times. Used coroutines, vector3.lerp etc. but nothing has worked.
Answer by Vandarthul · May 21, 2017 at 09:14 AM
Here is a simple script that does what you want by using both Lerp and SmoothDamp.
using UnityEngine;
public class SmoothDampTest : MonoBehaviour
{
private Transform myTransform;
private Vector3 velocity;
public bool useLerp;
public Vector3 target;
public float smoothTime;
public float lerpSpeed;
// Use this for initialization
void Start()
{
myTransform = transform;
}
// Update is called once per frame
void Update()
{
if (useLerp)
{
myTransform.localScale = Vector3.Lerp(myTransform.localScale, target, Time.deltaTime * lerpSpeed);
}
else
{
myTransform.localScale = Vector3.SmoothDamp(myTransform.localScale, target, ref velocity, smoothTime);
}
}
}
Attach it to a game object and try both Lerp and SmoothDamp to see if it's what you want. To use lerp:
Select the object that you've attached the script and set these variables on editor:
Use Lerp : true
Target : Set some target( note that if any of this value is 0, object might not be visible)
Lerp Speed: Some value(greater the value, faster the transaction)
To use SmoothDamp:
Use Lerp : false
Target : Set some target(note that if any of this value is 0, object might not be visible)
Smooth Time: Some value(lesser the value, faster the transaction, 0 is instant)
You can change the values in runtime by the way. This is to understand the behaviour and usage of lerp and smoothdamp. You need to prepare your own implementation(setting a percentage value with your start X value, in your case it's 10). Also please refer to this link to see the correct usage and details of Lerp. Lerp is not meant to produce a smoothing effect since it is a linear function but passing Time.deltaTime produces faster-start slower-end like effect since the t value is a percentage to target value.