- Home /
parrallax texture offset based on camera movement.
Hey all,
I was wondering if this was possible and how it would be achieved. I have a plane on my stage and a texture attached to it. Currently I scroll the texture based on a value like the following.
stars.renderer.material.SetTextureOffset("_MainTex", new Vector2(0,Time.time * paralaxScrollRatio));
But i was wondering if i could make it more dynamic and have it scroll based on the camera movement in either the x or y at a slower speed.
I was thinking it might be hard to do it based on camera movement. The effect I'm trying to achieve is scrolling parallax stars that scroll based on the direction and speed the camera is moving.
Has anyone got any thought on this. It would be much appreciated.
Answer by aldonaletto · Apr 01, 2012 at 01:51 PM
I suppose you could just multiply the camera position offset by a small factor and use this value to offset the texture - something like this (camera script):
public float factor = 0.001f; private Vector3 lastPos;
void Start(){ lastPos = transform.position; }
void Update(){ Vector3 shift = transform.position-lastPos; lastPos = transform.position; Vector2 offset; offset.x = -shift.x*factor; offset.y = -shift.y*factor; stars.renderer.material.SetTextureOffset("_MainTex", offset); } You may have to scramble the axes, depending on how your objects are aligned - kind of:
offset.y = -shift.z*factor;
offset.x = -shift.x*factor;
Thanks for the reply. I swear I submitted a comment on the day. $$anonymous$$ust not have submitted properly. I tried the code and I was getting a weird result or the offset only moving between something like 0.4 - 0.5. I couldn't see it moving at all so I tried the following.
Vector3 shift = mainCamera.transform.position - lastCameraPos;
lastCameraPos = mainCamera.transform.position;
Vector2 offset = stars.renderer.material.mainTextureOffset;
offset.x += -shift.x * 0.05f;
offset.y += -shift.y * 0.05f;
stars.renderer.material.SetTextureOffset("_$$anonymous$$ainTex", offset);
Which seems to work. Do you think its this is the best way to move the offset?
You're right: I forgot to increment the offset! It was just "shaking" the stars in my code, because the offset was based on the movement since last Update. It should be accumulated over time, like you did in your version - this way the starts move according to the camera displacement.
Your answer
Follow this Question
Related Questions
Using a 3D sphere in 2D space 2 Answers
parallax scrolling using orthographic camera 1 Answer
Mask to Camera? 0 Answers
Infinite Parallax Background 2 Answers
How to Manually Move the Camera Horizontally or Vertically? (2D, Parallax), 0 Answers