- Home /
Parallax scrolling
Hi, Im creating a 2d game where a character moves across a terrain. I decided to try out parallax scrolling where each plane is behind the other and adjusting the speed of the scrolling depending on their position relative to the camera. Closest scrolls fastest, etc. The main character (which is a bike) is stationary, but everything around it is scrolling giving the illusion that he's moving. The problem im having is that when the player lets go of the spacebar, the scrolling stops suddenly. Is there anyway I can make the scrolling speed up and slow down instead of stopping abruptly? This is my code so far:
public class parallax : MonoBehaviour {
public float Speed;
void Update () {
if (Input.GetButton("Horizontal")){
float mautToMove = Speed * Time.deltaTime;
transform.Translate(Vector3.left * mautToMove, Space.World);
}
}
}
Thanks!
Answer by Kiloblargh · Mar 08, 2013 at 05:00 AM
A good quick and dirty way to get smooth anything is with Mathf.Lerp(currentValue,finalValue,somethinglessthan1)
void Update () {
if (Input.GetButton("Horizontal"))
{
if (speedNow < maxSpeed)
{
speedNow = Mathf.Lerp(speedNow, maxSpeed, 0.4);
}
}
else
{
if (speedNow > 0)
{
speedNow = Mathf.Lerp(speedNow, 0, 0.2);
}
}
if (speedNow != 0)
{
mautToMove = speedNow * Time.deltaTime;
transform.Translate(Vector3.left * mautToMove, Space.World);
}
There are better ways that give you more control- doing this will always jump toward the final value quickly and then slowly settle in to it in a very nponlinear way. In theory it should never reach the target (Zeno's Arrow paradox) but it eventually gets floating point imprecision close and so will in fact finish.
This looks good for my UI buttons, who knows if it will look good for your bike, but it is a starting place.
Thanks for the reply, I tried this code but it doesn't seem to work. I've gotten quite a few errors
Your answer
Follow this Question
Related Questions
Vertical Parallax Scrolling 1 Answer
parallax scrolling background 2 Answers
How to deal with 2D parallax in a building? 0 Answers
2D Parallax Scrolling 1 Answer