Home > Software engineering >  How to slowly move an object in unity?
How to slowly move an object in unity?

Time:06-23

im trying to make slowly moving background. I have a code:

public void BackgroundMove(){
    bg.transform.Translate(Vector3.right * Time.deltaTime * bgspeed);
    bg.transform.Translate(-Vector3.up * Time.deltaTime * bgspeed);
    bg.transform.Translate(-Vector3.right * Time.deltaTime * bgspeed);
    bg.transform.Translate(Vector3.up * Time.deltaTime * bgspeed);
}

I call this function at Update(), but background moving all the sides simultaneously. What should I do?

CodePudding user response:

I'll give you code for moving it in a circle relative to its starting position. This code works by using sine and cosine to find points on a circle.

You could try to get by with the tangent and moving only the incremental position, but I would worry that varying Update() times would lead to integration errors and would eventually cause you to spiral out of position.

Make variables for how fast you want it to spin in Hertz and how large of a circle you want. Cache the starting position on Start() and then update the position in Update():

using UnityEngine;

public class Rotator : MonoBehaviour
{
    public GameObject bg;
    public float rotationRateHz = 0.5f;
    public float rotationRadius = 1.0f;
    private Vector3 startingPosition;
    private float phi;

    void Start()
    {
        startingPosition = bg.transform.position;
    }

    void Update()
    {
        float omega = rotationRateHz * 2.0f * Mathf.PI;
        phi  = omega * Time.deltaTime;
        float relativeX = rotationRadius * Mathf.Cos(phi);
        float relativeY = rotationRadius * Mathf.Sin(phi);
        Vector3 nextPosition = startingPosition;
        nextPosition.x  = relativeX;
        nextPosition.y  = relativeY;
        bg.transform.position = nextPosition;
    }
}

CodePudding user response:

The update method is called at every frame, so you can’t control complex moves within just that call. Instead, you can introduce states and timer to switch between states. You can use enum or Vector2 array.

private float timer = 0f;
private float periodTime = 2f;
private Vector2[] directions;
private int currentState = 0;

private void Awake(){
    directions = new Vector2[]{
        Vector3.right, Vector2.down, Vector2.left, Vector2.up};

    timer = periodTime;
}

private void Update(){
    bg.transform.Translate(directions[currentState] * speed * Time.deltaTime); 
    timer -= Time.deltaTime;

    if(timer <= 0){
        timer = periodTime;
        currentState = (currentState   1) % 4;
    }
}
  • Related