Equivalent of SKAction scaleToX for a given duration in Unity

后端 未结 1 1977
刺人心
刺人心 2021-01-20 16:44

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 increaseSp         


        
1条回答
  •  猫巷女王i
    2021-01-20 17:22

    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.

    0 讨论(0)
提交回复
热议问题