So I have a 2D character that moves in the screen with GetAxisRaw function and i’m for testing purposes relying on the update() method to move the char itself. Many 2D games have somesort of script that I tried to recreate that moves the various layers of the background at different speed, recreating thus a cool 3d looking environment while player moves.
Apparently I got how to move different background layers at different speed and all of this works except for the immense stuttering that I see at higher movement speed.
void Update ()
{
//Character Movement
GetAxis = Input.GetAxisRaw("Horizontal");
rigidbody2D.velocity = new Vector2(GetAxis * Velocity, rigidbody2D.velocity.y);
//if scrollbackground's set to true the following gets executed
if (ScrollBackground)
{
Background.transform.position = new Vector3(Background.transform.position.x + GetAxis * Velocity / 100, Background.transform.position.y, 5f);
}
}
feel free to ask for more details if the above seems right to you
IMPORTANT EDIT : this problem occurs if character movement is set with rigidbody2d.velocity property. changing it to a transform.position style movement would fix this, but I need the rigidbody in any case, any idea ?
First off, try FixedUpdate rather than Update. Since Update is called every frame, your background will actually move faster at higher frame rates. Not necessarily desirable. This might solve some of your problem. FixedUpdate is called at regular intervals, rather than every single frame.
It might be that what’s happening, or at least some of it, is that all of those quick transform calls are adding up to a decent little bit of strain on the processing system. Calling it all a little less frequently could reduce that strain. For a better solution, at higher velocities you could handle it in FixedUpdate, and handle lower velocities in Update.
Already tried it, the problem is still happening. I believe that this stuttering is caused by some part of the script that “teleports” the background back to it’s original position and then at the end of the frame gets moved again. I can’t really figure out which part of my code could do this “teleport back” neither i’m sure that this is happening
Assuming your background is a parallax background try this:
using UnityEngine;
using System.Collections;
public class GenericScrollScript: MonoBehaviour
{
public float speed = 0;
void Update()
{
renderer.material.mainTextureOffset = new Vector2((Time.time * speed)%1, 0f);
}
}