3

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.

humfrey
  • 31
  • 2

1 Answers1

2

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.

Community
  • 1
  • 1
Programmer
  • 121,791
  • 22
  • 236
  • 328
  • 2
    I am also trying to do something similar to (http://stackoverflow.com/questions/34768415/how-to-increase-animate-the-width-of-the-square-on-both-ends) using unity but I'm not too certain how to determine the scale by which to increase X for it to fill the whole width – NSSwift May 24 '16 at 05:56
  • @NSSwift screenWidth/spriteWidth is the scale you have to use to increase the sprite width to the screen width – NSologistic May 25 '16 at 17:27
  • 1
    @Programmer I don't know much C# but if NSSwift implements your solution with mine comment the sprite will extend off the screen if it's not in the center of the screen. You'll need to do some form of anchor point changing or so to keep the whole scaled sprite on the screen regardless of it's position. I believe that's what NSSwift wants to achieve. – NSologistic May 25 '16 at 17:33
  • @NSologistic This question was asked by humfrey and not by NSSwift. The original question is to re-size X to a new value which this answer does. He needs to ask a new question which he did. I am still trying to figure out how to help him do that. – Programmer May 25 '16 at 21:43