- Home /
How to make scrolling background to stop when player becomes idle?
I am new to unity. At present working on 2D game like Super Mario. Scrolling background is attached to moving camera. I want to make background to stop scroll when player becomes idle. My scrolling background script as below:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MovingBg : MonoBehaviour {
public float scrollSpeed = 0.01f;
void Update () {
Vector2 offset = new Vector2(Time.time * scrollSpeed, 0);
GetComponent<Renderer>().material.mainTextureOffset = offset;
}
}
Please help me out to solve the issue. Thank you
Answer by tormentoarmagedoom · Oct 03, 2018 at 07:49 AM
Good day.
You are moving the background with Time.time, which is the real time in the world. If you pretend to stop and play and stop and play the movement, you need some timer you can control, and not use the absolute Time.time
Easy way can be create your own timer, and stop/play the timer with player movement
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class MovingBg : MonoBehaviour {
public float scrollSpeed = 0.01f;
public float TimeForScroll = 0;
void Update () {
if (Player is moving)
{
TimeForScroll += Time.DeltaTime;
}
Vector2 offset = new Vector2(TimeForScroll * scrollSpeed, 0);
GetComponent<Renderer>().material.mainTextureOffset = offset;
}
}
Something like this, so when the player does not move, TimeForScroll will not change so offset will not change.
Bye!
Answer by Zodiarc · Oct 03, 2018 at 07:51 AM
Simply make the scrolling dependent on the player input. Use the same input that you use to move the player multiplied by -1 (since the background has to move in the opposite direction).
Using Input.GetAxis as an example:
Vector2 offset = new Vector2(Time.time * Input.GetAxis("Horizontal") * -1 * scrollSpeed , 0);
But this alone will cause snapping back of the background. You also need to store the current offset value, so this would be my solution:
public class Scroll: MonoBehaviour {
public Vector2 offset = new Vector2(0,0);
public float scrollSpeed = 1.0f;
public void Update() {
offset += new Vector2(Time.time * Input.GetAxis("Horizontal") * -1 * scrollSpeed , 0);
//assign offset here
}
}
I'd also suggest using Time.deltaTime instead of Time.time. You don't have to work with extremely small floats then.
Answer by vetesting9 · Oct 03, 2018 at 10:15 AM
Thank you guys for your reply. It worked fine for me.