Search code examples
c#unity-game-enginespritetranslationlerp

Unity: How to make a sprite move using Vector3.Lerp() without StartCoroutine


I want to move a sprite using Vector3.Lerp() without StartCoroutine. Starting and target points want to set in the script. I drag & drop the sprite into the Unity Editor and run it. However, the sprite doesn't move. Thanks.

using System.Collections;
using System.Collections.Generic;
using System.Threading;
using UnityEngine;

public class MyScript1 : MonoBehaviour {

public Sprite sprite;

GameObject gameObject;  
SpriteRenderer spriteRenderer;
Vector3 startPosition;
Vector3 targetPosition;

void Awake()
{
    gameObject = new GameObject();
    spriteRenderer = gameObject.AddComponent<SpriteRenderer>();        
}

private void Start()
{
    spriteRenderer.sprite = sprite;
    startPosition  = new Vector3(-300, 100, 0);
    targetPosition = new Vector3(100, 100, 0);        
}
void Update()
{        
    transform.position = Vector3.Lerp(startPosition, targetPosition , Time.deltaTime*2f);
}
}

Solution

  • Actually it does move but just a little and only once.

    The problem is in lerp method itself: Passing Time.deltaTime*2f as the third parameter is wrong.

    The third parameter of lerp method decides a point between startPosition and targetPosition and it should be between 0 and 1. it returns startPosition if 0 is passed and in your case it returns a point very very close to startPosition since you passed a very small number compared to the range (0..1)

    I suggest you read the unity docs about this method

    Something like this will work:

    void Update()
    {        
        t += Time.deltaTime*2f;
        transform.position = Vector3.Lerp(startPosition, targetPosition , t);
    }