Search code examples
androidunity-game-engineunityscript

Moving a gameObject with Animation outside update function


I checked how to move a gameObject with animation within the Update() function so you can use Time.deltaTime but I am trying to move the gameObject outside this function, and I also want to move the gameObject constantly (Travel on screen randomly). My current code without animation is:

    using UnityEngine;
using System.Collections;

public class ObjectMovement : MonoBehaviour
{
    float x1, x2;
    void Start()
    {
        InvokeRepeating("move", 0f, 1f);
    }
    void move()
    {
        x1 = gameObject.transform.position.x;
        gameObject.transform.position += new Vector3(Random.Range(-0.1f, 0.1f), Random.Range(-0.1f, 0.1f), 0);
        x2 = gameObject.transform.position.x;
        if (x2 < x1)
            gameObject.GetComponent<SpriteRenderer>().flipX = true;
        else
            gameObject.GetComponent<SpriteRenderer>().flipX = false;
    }
    void Update()
    {
    }
}

What is a better way of achieving this?


Solution

  • You could use Lerp to help you.

    Vector3 a, b;
    float deltaTime = 1f/30f;
    float currentTime;
    
    void Start()
    {
        InvokeRepeating("UpdateDestiny", 0f, 1f);
        InvokeRepeating("Move", 0f, deltaTime);
    }
    
    void Move()
    {
        currentTime += deltaTime;
        gameObject.transform.position = Vector3.Lerp(a, b, currentTime);
    }
    
    void UpdateDestiny()
    {
        currentTime = 0.0f;
        float x1, x2;
        a = gameObject.transform.position;
        x1 = a.x;
        b = gameObject.transform.position + new Vector3(Random.Range(-0.1f, 0.1f), Random.Range(-0.1f, 0.1f), 0);
        x2 = b.x;
        if (x2 < x1)
            gameObject.GetComponent<SpriteRenderer>().flipX = true;
        else
            gameObject.GetComponent<SpriteRenderer>().flipX = false;
    }