Search code examples
animationunity-game-enginetween

Animate/move/translate/tween image in Unity 4.6 from C# code


How can I move/animate/translate/tween an Image from position A to position B using C# code in Unity 4.6?

Assuming Image is a GameObject, so it could be a Button or whatever. There has to be a one-liner for this, right? I've been googling for a while but all I can see out-of-the-box is stuff done in Update, and I firmly believe doing stuff in Update is not a fast way of scripting things.


Solution

  • If you want to do the movement yourself you can use something like this:

    public Vector3 targetPosition = new Vector3(100, 0, 0);
    public float speed = 10.0f;
    public float threshold = 0.5f;
    void Update () {
        Vector3 direction = targetPosition - transform.position;
        if(direction.magnitude > threshold){
            direction.Normalize();
            transform.position = transform.position + direction * speed * Time.deltaTime;
        }else{ 
            // Without this game object jumps around target and never settles
            transform.position = targetPosition;
        }
    }
    

    Or you can download for example DOTween package and just start the tween:

    public Vector3 targetPosition = new Vector3(100, 0, 0);
    public float tweenTime = 10.0f;
    void Start () {
        DOTween.Init(false, false, LogBehaviour.Default);
        transform.DOMove(targetPosition, tweenTime);
    }