Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Equivalent of SKAction scaleToX for a given duration in Unity

I am trying to scale the x axis of a sprite over a given duration in Unity. Basically I've done this before using Swift in the following way,

let increaseSpriteXAction = SKAction.scaleXTo(self.size.width/(mySprite?.sprite.size.width)!, duration:0.2)
mySprite!.sprite.runAction(increaseSpriteXAction)
mySprite!.sprite.physicsBody = SKPhysicsBody(rectangleOfSize:mySprite!.sprite.size, center: centerPoint)

but haven't even found an equivalent for scaleToX in Unity. I'll really appreciate some assistance.

like image 691
humfrey Avatar asked Dec 18 '25 05:12

humfrey


1 Answers

Use combination Coroutine, Time.deltaTime and Mathf.Lerp then pyou will be able to replicate the function of SKAction.scaleXTo function.

bool isScaling = false;

IEnumerator scaleToX(SpriteRenderer spriteToScale, float newXValue, float byTime)
{
    if (isScaling)
    {
        yield break;
    }
    isScaling = true;

    float counter = 0;
    float currentX = spriteToScale.transform.localScale.x;
    float yAxis = spriteToScale.transform.localScale.y;
    float ZAxis = spriteToScale.transform.localScale.z;

    Debug.Log(currentX);
    while (counter < byTime)
    {
        counter += Time.deltaTime;
        Vector3 tempVector = new Vector3(currentX, yAxis, ZAxis);
        tempVector.x = Mathf.Lerp(currentX, newXValue, counter / byTime);
        spriteToScale.transform.localScale = tempVector;
        yield return null;
    }

    isScaling = false;
}

To call it:

public SpriteRenderer sprite;
void Start()
{
    StartCoroutine(scaleToX(sprite, 5f, 3f));
}

It will change the x-axis scale from whatever it is to 5 in 3 seconds. The-same function can easily be extended to work with the y axis too.

Similar Question: SKAction.moveToX.

like image 78
Programmer Avatar answered Dec 21 '25 23:12

Programmer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!