- Home /
renderer.material.mainTextureOffset based on player movement
Hi everbody I've searched for methods on how to make parallax scrolling background and ended up using a second camera that films the background textures and projects them at the background of the main camera. This works fine BUT I only want the background to move when the player move because I'm making a 2d platformer. How do I do it?
This is the script for moving the offset of the textures
public float speed = 0;
void Update () {
renderer.material.mainTextureOffset = new Vector2 (Time.time * speed, 0f);
}
I tried this
void Update () {
if (Input.GetKey ("d")){
renderer.material.mainTextureOffset = new Vector2 (Time.time * speed, 0f);
}
if (Input.GetKey ("a")){
renderer.material.mainTextureOffset = new Vector2 (Time.time * -speed, 0f);
}
}
And it kinda works... but the textures makes a big "jump" everytime I press "d" or "a" but after that is looks fine. But another problem is that if the player walks into a wall and keep pressing the d or a keys the background ofc still moves. What is the best way to make the offset change based on player movement?
Why don't you link the offset to the player's position ins$$anonymous$$d of key input? Because as ou rightly observe the keys can be pressed even if the player does not move.
renderer.material.mainTextureOffset = new Vector2 (playerObject.transform.x * factor, 0f);
Now you only need to create a public GameOject playerObject and assign the player's object to it in the inspector and another public float factor that could be set to 0.5f for a start and see if this is what you need. :-)
Thanks gnometech :D
I did this
renderer.material.mainTextureOffset = new Vector2 (GameObject.FindGameObjectWithTag("Player").transform.position.x * speed, 0f);
and it works perfect. How do I vote your answer the best answer? :S
Your answer
Follow this Question
Related Questions
Offset textures individually into specific world directions 2 Answers
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Read Y offset value of a Texture 1 Answer
I'm trying to get a picture in game and display it on a plane 2 Answers