-1

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?

  • If you don't want all sides to move simultaneously, why do the 4 lines you have move it in all 4 directions at the same time? "slowly move" is a very vague definition. Please include more details of your intended result. – Jesse Jun 22 '22 at 18:27
  • [video of what i want](https://youtu.be/NRZrybXNyg8) like that –  Jun 22 '22 at 19:18

2 Answers2

1

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;
    }
}
Chuck
  • 1,977
  • 1
  • 17
  • 23
1

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;
    }
}
JottoWorol
  • 281
  • 2
  • 9