Equivalent of SKAction scaleToX for a given duration in Unity

假装没事ソ 提交于 2019-12-04 04:41:37

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/37388496/equivalent-of-skaction-scaletox-for-a-given-duration-in-unity

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!