Add this simple script to make your 2D games stand out with a nice depth effect! 🎮 Play 7 Awesome Games (Action, Strategy, Management) and Help Support the Channel! ✅ Get the Game Bundle 67% off unitycodemonkey.com/gameBundle.php
It is amazing how every single 15-20 minutes video from Code Monkey leads yourself into an hour or even days of deep learning into Unity if you are open to really understand all the aspects of what he is teaching. Excellent content as always !!! Thanks a lot !
You pronunciation is so clear that I watch your videos in 2x speed and I can still comprehend what you're saying. Amazing, thank you for the efficiency boost.
I just hope that one day you won't delete all your videos because they are sooo valuable, I am planning to watch them all from beginning sometime Thank you for this amazing value you are giving us!
Thanks for this CodeMonkey, really appreciate this. Now, if your parallax is still jittering/ lagging: try one of the following methods, hopefully they might work: - Try alternating between FixedUpdate() and LateUpdate() - Try changing the Interpolation on the player(Interpolate or Extrapolate or None). Try combinations with the above step - Lastly, this worked for me: Try changing the pixel size of the sprites by clicking on the sprite and not the object. Mine was 100, but when I changed it to 64, it ran butter smooth
thank you for awesome video , one thing for people who want to use your Script for their project , if you change Scale of your picture ... movement of the picture would not be smooth as the video and thats because texture unit size assume Scale is at one ... so only thing you have to do is to multiply textureUnitSizeX and textureUnitSizeY with transform.localScale.x and transform.localScale.y ... again thank you Code Monkey for amazing videos :) love from an indie dev from IRAN ...
Thanks a lot man i solved all my problems , 4 hours spent on creation big level of my game using a parallax and Cinemachine + drawing my own sprites. Ur vid is great!!!
Super useful tutorial! 👍 Only thing, when I used this with the cinemashine I needed to change the LateUpdate() to fixedUpdate(). Probably because the CM is Updating the camera in fixed Updates 🤔
It was exactly solution for what i was looking for. Other tutorials can be deleted. Had only problems with layer ordering while using some weird method like puting image on plane object or it wasnt working at all. By the way i like your code style. You do it like normal not amatour.
Hello Code Monkey! Currently I'm making a 2d sidescroller in a pixelart style, and I tried to implement this infinite parallax background. I wrote the exact lines in my script (after failing multiple times I've downloaded the assets, and just copied the script.) but it did not work. Instead of the "background jumping to the other side" mine is kinda following the camera (like I have a wide background object and it keeps stuttering, and it only shows one part). Please, if you could help that would really make my day!
Hello Code Monkey, is there a reason that you turned start() update() into the private? the variable parallaxEffectMultiplier could be public, if it's public, it would appear in the inspector ( when it's private, you need to write [SerializeField] in order to show on the inspector.)?
Making a variable public not only exposes it to the editor it also exposes it to the rest of your entire project. So if you have something that is meant to be modified solely in the script and in the editor, make it private and add [SerializeField], that will keep you code nice and clean and make it obvious that no other script will ever touch that field. Start(); and Update(); should always be private, no other script should ever call those.
Yeah that's definitely something I'd like to cover more. I was going to make a complete game like Terraria but had to switch to the Top Down Shooter game because there are still tons of Platformer elements that I haven't covered.
Great video thank you so much!! You saved my day! I assume it doesn't make much difference but substracting the offsetPosition from the transform.position seems more natural for me. Sorry if I got it wrong! I'm just a beginner.
Hi @CodeMonkeyUnity, I am amazed to see that you have still responded to some relatively recent comments and it has given me hope to ask a question. I think I followed the video without errors, but I have a problem with the parallax because when you have to jump seamlessly there is a clear jump. I have been touching the dimensions of my background, I don't know if that could be causing the error. Any help would be appreciated.
It works seamlessly horizontally but not vertically? The issue will be something related to the math and/or the size of the texture. Maybe you're applying the same offset on the X and Y even though it has different width/height? Look at the scene view while playing to see exactly what is going wrong, is it jumping too much or too little? Add some logs to see what values you're working with
A small improvment I found was to change the the lastCameraPosition in the start() from camera position to Vector3.Zero Let's say you build your level with the camera in a certain place, and playtest. looks good. Now if you change the camera position and play again, the parallax start in a place relative to the camera position and this messes things up a little (I found it the hard way). with vector3.zero it will aways have the deffault editor start position.
Hi! I have a random question: when getting the sprite for the game object, why do you call GetComponent().sprite instead of GetComponent() ? To me it sounds like they do the same thing, is there like a small difference between the two? Your videos are incredible, by the way, they are lifesavers!
There is no Sprite component that you attach to a GameObject, just a SpriteRenderer so you cannot do GetComponent(); you need to get the SpriteRenderer and find the sprite attached to it I'm glad my videos have helped you! Thanks!
@Code Monkey: can you check your script with scaled transformation on background graphic? if i scale my graphics up than the background jumps on x-axis if it was moved. I think I have to calculate the texture-width on another way but I didn't understand how. :(
Ok so everything is working fine other than the clouds are not infinite for some reason and I cannot seem to figure out why. I have toggled off the vertical bool and that's not seeming to help the issue.
Great video! I'd like to ask if there's a way to make the background (a static background) always fit the player screen. I've tried many things but it never worked.
When i scale sprite game objects in Inspector, parallax lags. how can i scale sprites without lag? I use single sprite mode with full rect and 2000 width for tiling
Someone has by any chance a tip that this could work if I change the size of the camera ? My target is that the camera go back more the character run fast. :) It's working by setting the camera on perspective mode but is it good ?
Hey, Can you think of any reason why this script might not work for me? The general parallax effect works great but after adding the if statement to LateUpdate the images don't align on transition at all. Using a virtual camera rather than a regular camera in my project. If I can't find a solution, would it be acceptable to just have a very long parallax background instead? Cheers.
I think that I am facing the same issue. When the background repositions itselfs, there is a small jump. It almost fit perfectly, but we can still notice that it is not aligned. I've copied perfectly and double checked almots everything but it still does it.. If you've found a solution it woud be so much appreciated ! thanks
Would you consider updating this or giving some additional instructions on getting it to work with Unity 2022? I've tried several times, even re-installed Unity 2019. I haven't been able to get it to run as displayed in the video. The biggest issue is the player is "invisible" but the background is moving around nicely. After playing around with the shader settings (I'm a novice) I was able to see a blocky white player-like object moving around the screen. Please and thank you!
There's nothing here that is dependent on a specific Unity version. Sound like you just have an issue with your sorting layers, not shaders unitycodemonkey.com/video.php?v=5_BwFB-1dAo
Hey, thank you so much for the video! Can you please explain why you're adding offsetPositionX to the new background position and why did you calculate it in the way you did?
It needs to be perfectly calculated so that when it snaps to a different position the effect is invisible, if you don't calculate it perfectly then you will see the background "move" instead of flawlessly repeating
@@CodeMonkeyUnity Thanks for the explanation, I understand that this is meant to make the snapping invisible to the user, my question is why does this achieve this?
@@resistancefighter888 Вообще более правильно сделать camera.position.x - offsetPositionX. В данном случае это может быть несущественным, т.к. если изображение достаточного высокого разрешения, то склейка со смещением в пару пикселей не будет заметна, но это может стать заметным на более мелком разрешении. Достигается это за счёт того, что offsetPositionX вычисляется таким образом, что он всегда кратен ширине повторяющейся части фона и сдвигается ровно на то расстояние, на котором идёт повтор. Таким образом мы за один кадр перемещаем повторяющуюся зону вперед или назад и оно идеально стыкуется и кажется, что картинка не двигалась.
I made same script like in this video, put same values and setting for sprites, it's noticeable that they're snapping, Is it supposed to be like this or did I do something wrong? I put video in United Programming server
so for whatever reason, the background elements that i add the script to are very shaky and unstable, nothing like the smooth effect you're getting.... any ideas?
the script is not working for me i get an error i says: transform.position assign attempt for 'clouds_4' is not valid. Input position is { NaN, -4.730000, 0.000000 }. UnityEngine.Transform:set_position(Vector3) ParallaxBackground:LateUpdate() (at Assets/Scripts/ParallaxBackground.cs:31) how to fix this? i dont know how but great vids.
Hi, the movement of the background goes to move, jitters, and then resets back to its original position? Is this something I can solve? I am using Cinemachine as a camera and the background witth the effect applied is a child of the CM vcam1.Thanks
Kinda nice, but can't get it working. When the background layers re-position themselves, they don't align and there is an obvious jump. I've experimented with parameters but no success. In the video, you skim over the section about setting the edge of the texture too quickly, there's no detail. What can I do to fix this? Thanks.
@@CodeMonkeyUnity I am facing the same issue. When the background repositions itselfs, there is a small jump. I've copied perfectly and double checked almots everything but it still does it.. Have you found a solution curb47 ? Would be greatly appreciated !
I know it's a year later but I copied everything you did on the video fine and it worked but when I made a new project and I did everything again. everytime I moved horizontally or vertically it's snaps the background so I can see in game that It is definitely moving and it doesn't look smooth any suggestions?
thanks for the tutorial. i followed everything and i keep getting "object reference not set to an instance of an object" and the error comes from vector 3 line 24 in your code
I'm having an issue where moving up/down the background does not seamlessly move to where it should be. I double checked the sprite renderer size and it's set properly to the default values when you first drag in the background * 3. Should those default values not be trusted or what.. super inconsistent anyway, sometimes it moves perfectly seamlessly and sometimes not..
my background sprite turns into just 1 plain color when i change the draw mode to tiled. it looks normal in the other 2 modes, but tiled mode doesnt work. its just a rectangle.
how do u manage enemy damage per levels do u use formal? because if player bought weapon and armor will kill enemy easy so game will be boring i don't want to make game very hard or very easy can u help with that Thanks
Thanks for the video, but I really dont get it. I dont want to blindly copy-paste what you do, but rather understand the logic. Some more explanation of what you're doing would help immensely. RIght now, there are times where you just type without any comment. Could you please explain the logic in more detail? :)
@@CodeMonkeyUnity First of all, thanks so much for replying! Secondly - I get lost as soon as you go past 9:40. You introduce a lot of classes (Sprite, Texture 2D) and then proceed to explain what purpose they *serve*, but I just don't get what they *do*. Being a rookie, this is pretty much the first time I get to see them. ;) What does sprite vs texture do (why the differentiation)? What point does pixelsperunit serve? Being a coder I understand the C#, but unity - specific elements are a mystery to me. Some more in-depth narrative would help a lot!
@@Jimbeksus Check out the basics playlist which will help you get familiar with the basic elements of Unity like Game Objects, Sprites, etc ua-cam.com/play/PLzDRvYVwl53vxdAPq8OznBAdjf0eeiipThttps.html://ua-cam.com/play/PLzDRvYVwl53vxdAPq8OznBAdjf0eeiipT.html A Sprite in Unity is essentially a texture with some extra options, check the import options for any texture in your project files and you'll see the Pixels Per Unit. Thats how many Pixels of the texture should fit in 1 Unit in the game world.
For me, the code shown in the video doesn't work for creating the vertical infinite. However, it does work for the X axis, and I also can move for the Y axis, except that for the Y axis, it is not infinite... too bad. Here is my code: using UnityEngine; using System.Collections; using System.Collections.Generic; public class ParallaxBackground : MonoBehaviour { [SerializeField] private Vector2 parallaxEffectMultiplier; private Transform cameraTransform; private Vector3 lastCameraPosition; private float textureUnitSizeX; private float textureUnitSizeY; private void Start() { cameraTransform = Camera.main.transform; lastCameraPosition = cameraTransform.position; Sprite sprite = GetComponent().sprite; Texture2D texture = sprite.texture; textureUnitSizeX = texture.width / sprite.pixelsPerUnit; textureUnitSizeX = texture.height / sprite.pixelsPerUnit; } private void FixedUpdate() { Vector3 deltaMovement = cameraTransform.position - lastCameraPosition; transform.position += new Vector3(deltaMovement.x * parallaxEffectMultiplier.x, deltaMovement.y * parallaxEffectMultiplier.y); lastCameraPosition = cameraTransform.position; if (Mathf.Abs(cameraTransform.position.x - transform.position.x) >= textureUnitSizeX) { float offsetPositionX = (cameraTransform.position.x - transform.position.x) % textureUnitSizeX; transform.position = new Vector3(cameraTransform.position.x + offsetPositionX, transform.position.y); } /* if (Mathf.Abs(cameraTransform.position.y - transform.position.y) >= textureUnitSizeY) { float offsetPositionY = (cameraTransform.position.y - transform.position.y) % textureUnitSizeY; transform.position = new Vector3(transform.position.x, cameraTransform.position.y + offsetPositionY); }*/ } }
I had a 2.5D game, with3D characters, platforms and objects etc on Z=0. Imagine Little Big Planet. I need to set up an infinite scrolling background like this, but it only seems to work when the sprites are on Z=0, which obviously intersect with my game objects. Is this technique strictly ONLY for completely flat 2D sprite based games? Thanks.
If your camera is 3D then you don't need this since you have Parallax by default, just place your backgrounds at different Z positions. The further an object is from the camera the slower it will appear to move.
@@CodeMonkeyUnity Yes, I understand that, but to get the kind of of parallax you demonstrate in your tutorial, the horizon layer will have to be really far away on the Z, and a huge image. Is there not a performance hit if images are hugs, or scaled up? Thanks.
I know it's a long shot because of the age of the video, but with the [SerializedField] I am getting an error in unity that says "the type or namespace name "SerializedField" could not be found" am I doing anything incorrect?
Add this simple script to make your 2D games stand out with a nice depth effect!
🎮 Play 7 Awesome Games (Action, Strategy, Management) and Help Support the Channel!
✅ Get the Game Bundle 67% off unitycodemonkey.com/gameBundle.php
pls help, for me the hills dont snap smoothly in position. They change their position and you can see it very obviusly.
It is amazing how every single 15-20 minutes video from Code Monkey leads yourself into an hour or even days of deep learning into Unity if you are open to really understand all the aspects of what he is teaching. Excellent content as always !!! Thanks a lot !
I'm glad the videos helped you! Thanks!
You pronunciation is so clear that I watch your videos in 2x speed and I can still comprehend what you're saying. Amazing, thank you for the efficiency boost.
Thank you for pointing this out, just saved 8 minutes or whatever
This is so stinking good, it's simple and solid. I've written a couple of these and this is now my go to...
I just hope that one day you won't delete all your videos because they are sooo valuable, I am planning to watch them all from beginning sometime
Thank you for this amazing value you are giving us!
Thanks for this CodeMonkey, really appreciate this. Now, if your parallax is still jittering/ lagging: try one of the following methods, hopefully they might work:
- Try alternating between FixedUpdate() and LateUpdate()
- Try changing the Interpolation on the player(Interpolate or Extrapolate or None). Try combinations with the above step
- Lastly, this worked for me: Try changing the pixel size of the sprites by clicking on the sprite and not the object. Mine was 100, but when I changed it to 64, it ran butter smooth
how do I click on the sprite instead of the object?
OH MY GOD THANK YOU
@@ceoofbananaco.9960 keep passing the knowledge ahead!
you are awesome, this works for player "check point" system
thank you for awesome video , one thing for people who want to use your Script for their project , if you change Scale of your picture ... movement of the picture would not be smooth as the video and thats because texture unit size assume Scale is at one ... so only thing you have to do is to multiply textureUnitSizeX and textureUnitSizeY with transform.localScale.x and transform.localScale.y ... again thank you Code Monkey for amazing videos :)
love from an indie dev from IRAN ...
Thanks a lot man i solved all my problems , 4 hours spent on creation big level of my game using a parallax and Cinemachine + drawing my own sprites. Ur vid is great!!!
I programmed this myself just recently - but your code is so much better and flexible. Will adapt it tomorrow. Thanks!!
I've tried to write a few of these on my own.... But it was never as simple, robust, and expandable as yours... Thank you so much
I'm glad you found it useful!
Still works 4 years later so thanks bud!
You're always writing such simple stuff in more advanced way, I didn't know when to use mod operator, keep it up! :D
I love you!! Thats exactly what I was searching for!! 😀😂
Another video really well done and simple to follow. I just love it !
This is by far the best video on Parallaxing.
Awesome tutorial. Been scratching my head a long time over this, happy to find such an easy solution
Super useful tutorial! 👍
Only thing, when I used this with the cinemashine I needed to change the LateUpdate() to fixedUpdate(). Probably because the CM is Updating the camera in fixed Updates 🤔
Clever. Impressive simplicity. You rock.
I really like the walking animation.
It was exactly solution for what i was looking for. Other tutorials can be deleted. Had only problems with layer ordering while using some weird method like puting image on plane object or it wasnt working at all. By the way i like your code style. You do it like normal not amatour.
Hello Code Monkey! Currently I'm making a 2d sidescroller in a pixelart style, and I tried to implement this infinite parallax background. I wrote the exact lines in my script (after failing multiple times I've downloaded the assets, and just copied the script.) but it did not work. Instead of the "background jumping to the other side" mine is kinda following the camera (like I have a wide background object and it keeps stuttering, and it only shows one part). Please, if you could help that would really make my day!
Once again, your way is the best! thank's for your content
It was awesome , keep making such videos.
It will be really good if you cover some 3d topic also.
I wish I could like this video as many times as I can click like for it's duration of the video
Hello Code Monkey, is there a reason that you turned start() update() into the private? the variable parallaxEffectMultiplier could be public, if it's public, it would appear in the inspector ( when it's private, you need to write [SerializeField] in order to show on the inspector.)?
Making a variable public not only exposes it to the editor it also exposes it to the rest of your entire project.
So if you have something that is meant to be modified solely in the script and in the editor, make it private and add [SerializeField], that will keep you code nice and clean and make it obvious that no other script will ever touch that field.
Start(); and Update(); should always be private, no other script should ever call those.
Can you please tell me what to do if the new position.x of the background does not exactly fit the previous one?
I was just looking at tuts for this!!
Is this the start of Side Scroll game tutorials? God Bless you!
Yeah that's definitely something I'd like to cover more. I was going to make a complete game like Terraria but had to switch to the Top Down Shooter game because there are still tons of Platformer elements that I haven't covered.
THE ULTIMATE GUIDE!
Great video thank you so much!! You saved my day!
I assume it doesn't make much difference but substracting the offsetPosition from the transform.position seems more natural for me. Sorry if I got it wrong! I'm just a beginner.
Я тоже заметил это. Я думаю это ошибка и она будет заметна, если размер повторяющейся зоны будет маленький
@@JanMihail Why, thank you!
I'm happy that someone is on the same page. :)
Excellent work! Thank you.
THIS WAS SUPER HELPFUL
Working beautiful, thanks!
I did everything till 6:13 and when I test the game, the background layers dont move at all anymore. What the f am I doing wrong? :(
I don't know I to thank you
You really are smart
I am trying with this code but the background moving with camera but not adjusting with the previous background.
Thank god I saw your ad moths ago it was worth it
Hi @CodeMonkeyUnity,
I am amazed to see that you have still responded to some relatively recent comments and it has given me hope to ask a question. I think I followed the video without errors, but I have a problem with the parallax because when you have to jump seamlessly there is a clear jump. I have been touching the dimensions of my background, I don't know if that could be causing the error. Any help would be appreciated.
It works seamlessly horizontally but not vertically?
The issue will be something related to the math and/or the size of the texture. Maybe you're applying the same offset on the X and Y even though it has different width/height?
Look at the scene view while playing to see exactly what is going wrong, is it jumping too much or too little? Add some logs to see what values you're working with
Thank you so much! You're amazing!
You must type really fast, based on the very super fast keyboard typing sounds.
No, but seriously very good tutorial .
Great videovand great effect )
Thanks man! You saved my day! :)
Very simple and very powerful to use, thanks! =)
A small improvment I found was to change the the lastCameraPosition in the start()
from camera position to Vector3.Zero
Let's say you build your level with the camera in a certain place, and playtest. looks good.
Now if you change the camera position and play again, the parallax start in a place relative to the camera position and this messes things up a little (I found it the hard way).
with vector3.zero it will aways have the deffault editor start position.
Finaly something that works for me thank you
the light mode burns my eyesssss
Sorry but dark mode burns my eyes
Thank you so much! Awesome! 8)
Hi! I have a random question: when getting the sprite for the game object, why do you call GetComponent().sprite instead of GetComponent() ? To me it sounds like they do the same thing, is there like a small difference between the two? Your videos are incredible, by the way, they are lifesavers!
There is no Sprite component that you attach to a GameObject, just a SpriteRenderer so you cannot do GetComponent(); you need to get the SpriteRenderer and find the sprite attached to it
I'm glad my videos have helped you! Thanks!
@Code Monkey:
can you check your script with scaled transformation on background graphic? if i scale my graphics up than the background jumps on x-axis if it was moved. I think I have to calculate the texture-width on another way but I didn't understand how. :(
Didnt know if i'm in time, but if you scale up your sprite simply multiply it with transform.localscale in textureunitsizeX
@@Howdyhowthis I know it's been ages since but thank you so much, I've been struggling with this for a while now, you're a life saver!
@@Asheroonis I was struggling with that for a while too. Glad I'm leaving that comment there. Good luck with your project!
Ok so everything is working fine other than the clouds are not infinite for some reason and I cannot seem to figure out why. I have toggled off the vertical bool and that's not seeming to help the issue.
I tried implementing this to my game but when I built it to android the background kept blinking, any idea how to fix it?
Anyone using Cinemachine - change LateUpdate => FixedUpdate. It will stop the jittering.
Amazing, thanks for that! 👍
Nice tutorial. But as I am a beginner, I really hope that you will make a tutorial of it using Bolt Visual Scripting. Thank you.
Beautiful.
How can I make this effect if my character doesn't move, but only jumps, like the flappy bird?
It's the exact same thing, you just have different layers moving at different speeds, doesn't matter if they're moving in the X or Y axis
Every so often, the texture jumps and its quite noticable that the image has moved. Has anyone experienced this ?
Great video! I'd like to ask if there's a way to make the background (a static background) always fit the player screen. I've tried many things but it never worked.
That requires doing some math based on the texture size, sprite pixelsPerUnit and Screen.width and Screen.height
@@CodeMonkeyUnity Does the code that you showed in this video helps with that? If not, do you have one video on the subject? Thanks for the answer!
I was exactly with your code but, instead my player movement scripts didn't work
When i scale sprite game objects in Inspector, parallax lags. how can i scale sprites without lag? I use single sprite mode with full rect and 2000 width for tiling
I followed your instructions to create a parallax background, but mine is still showing clear snaps when it triggers. Not useful
Then you did something wrong, computers are deterministic, if you do exactly what I show in the video you will get exactly the same result.
Someone has by any chance a tip that this could work if I change the size of the camera ? My target is that the camera go back more the character run fast. :)
It's working by setting the camera on perspective mode but is it good ?
Note that if you use scaling this doesn't factor that in. I had to multiply textureUnitSizeX by transform.localScale.x.
OMG. thanks! =)
You are awesome. Had to scroll a lot to reach this. But worth it. Thanks!
Thank you very much
I subscribed because you don't shove your face to the camera like other Unity coders.
Hey,
Can you think of any reason why this script might not work for me? The general parallax effect works great but after adding the if statement to LateUpdate the images don't align on transition at all. Using a virtual camera rather than a regular camera in my project.
If I can't find a solution, would it be acceptable to just have a very long parallax background instead?
Cheers.
Did you find a solution ? Got the same problem
I think that I am facing the same issue. When the background repositions itselfs, there is a small jump.
It almost fit perfectly, but we can still notice that it is not aligned.
I've copied perfectly and double checked almots everything but it still does it..
If you've found a solution it woud be so much appreciated ! thanks
Did you or anyone figure out why? Got the same issue
You inspire me!
Glad to hear it!
I just set X Multiplier to 0.9 but its still too fast for me! how can I make it slower?
Would you consider updating this or giving some additional instructions on getting it to work with Unity 2022? I've tried several times, even re-installed Unity 2019. I haven't been able to get it to run as displayed in the video. The biggest issue is the player is "invisible" but the background is moving around nicely. After playing around with the shader settings (I'm a novice) I was able to see a blocky white player-like object moving around the screen. Please and thank you!
There's nothing here that is dependent on a specific Unity version.
Sound like you just have an issue with your sorting layers, not shaders unitycodemonkey.com/video.php?v=5_BwFB-1dAo
Hey, thank you so much for the video! Can you please explain why you're adding offsetPositionX to the new background position and why did you calculate it in the way you did?
It needs to be perfectly calculated so that when it snaps to a different position the effect is invisible, if you don't calculate it perfectly then you will see the background "move" instead of flawlessly repeating
@@CodeMonkeyUnity Thanks for the explanation, I understand that this is meant to make the snapping invisible to the user, my question is why does this achieve this?
@@resistancefighter888 Вообще более правильно сделать camera.position.x - offsetPositionX. В данном случае это может быть несущественным, т.к. если изображение достаточного высокого разрешения, то склейка со смещением в пару пикселей не будет заметна, но это может стать заметным на более мелком разрешении. Достигается это за счёт того, что offsetPositionX вычисляется таким образом, что он всегда кратен ширине повторяющейся части фона и сдвигается ровно на то расстояние, на котором идёт повтор. Таким образом мы за один кадр перемещаем повторяющуюся зону вперед или назад и оно идеально стыкуется и кажется, что картинка не двигалась.
I made same script like in this video, put same values and setting for sprites, it's noticeable that they're snapping, Is it supposed to be like this or did I do something wrong? I put video in United Programming server
great video. thanks
so for whatever reason, the background elements that i add the script to are very shaky and unstable, nothing like the smooth effect you're getting.... any ideas?
to add to this, it's only happening in my game window, it looks great in the scene window
the script is not working for me i get an error i says: transform.position assign attempt for 'clouds_4' is not valid. Input position is { NaN, -4.730000, 0.000000 }.
UnityEngine.Transform:set_position(Vector3)
ParallaxBackground:LateUpdate() (at Assets/Scripts/ParallaxBackground.cs:31)
how to fix this? i dont know how but great vids.
Thank you!
it works, but in pixel art when pictures are much smaller but scaled up it looks jaggy
Why is my background moving backwards on the Z axis :(
Hi, the movement of the background goes to move, jitters, and then resets back to its original position? Is this something I can solve? I am using Cinemachine as a camera and the background witth the effect applied is a child of the CM vcam1.Thanks
It moves then moves back? Sounds like you have some conflicting logic, add some Debug.Log's to see what your code is doing
Kinda nice, but can't get it working. When the background layers re-position themselves, they don't align and there is an obvious jump. I've experimented with parameters but no success. In the video, you skim over the section about setting the edge of the texture too quickly, there's no detail. What can I do to fix this? Thanks.
The texture just needs to repeat itself. The code teleports it into the exact perfect position.
@@CodeMonkeyUnity I am facing the same issue. When the background repositions itselfs, there is a small jump.
I've copied perfectly and double checked almots everything but it still does it..
Have you found a solution curb47 ? Would be greatly appreciated !
@@theAmbroise16 did u fixed that? bcs now i am strugglin on it. Please help
muchas gracias gran maestro por el tutorial
Thank you so much
Where are the best place to get utilities for making games when making and selling games?
What if I want to add stuff to the scrollimg background that appear randomly but gets harder the more the player goes forward?
Thanks! :D
I know it's a year later but I copied everything you did on the video fine and it worked but when I made a new project and I did everything again. everytime I moved horizontally or vertically it's snaps the background so I can see in game that It is definitely moving and it doesn't look smooth any suggestions?
I think LateUpdate() is the issue. I had to change everything to Update() for it to work.
Guys what to do when the mountains snap? It snaps whenever I move pls help
thanks for the tutorial. i followed everything and i keep getting "object reference not set to an instance of an object" and the error comes from vector 3 line 24 in your code
Use Debug.Log to find what is null unitycodemonkey.com/video.php?v=5irv30-bTJw
very good!!
Why it not works smooth with cinemamachine?
I'm having an issue where moving up/down the background does not seamlessly move to where it should be. I double checked the sprite renderer size and it's set properly to the default values when you first drag in the background * 3. Should those default values not be trusted or what..
super inconsistent anyway, sometimes it moves perfectly seamlessly and sometimes not..
try putting everything in FixedUpdate
my background sprite turns into just 1 plain color when i change the draw mode to tiled. it looks normal in the other 2 modes, but tiled mode doesnt work. its just a rectangle.
click on your asset and change the import setting: Mesh Type from Tight to Full Rect.
how do u manage enemy damage per levels do u use formal?
because if player bought weapon and armor will kill enemy easy so game will be boring
i don't want to make game very hard or very easy can u help with that
Thanks
if your parallax is still lagging, Maybe it's because you scale the picture up
Hi I think you can make an array for background elements. Then we can add as many background assets we want.
Thanks for the video, but I really dont get it. I dont want to blindly copy-paste what you do, but rather understand the logic. Some more explanation of what you're doing would help immensely. RIght now, there are times where you just type without any comment. Could you please explain the logic in more detail? :)
What don't you get?
@@CodeMonkeyUnity First of all, thanks so much for replying! Secondly - I get lost as soon as you go past 9:40. You introduce a lot of classes (Sprite, Texture 2D) and then proceed to explain what purpose they *serve*, but I just don't get what they *do*. Being a rookie, this is pretty much the first time I get to see them. ;) What does sprite vs texture do (why the differentiation)? What point does pixelsperunit serve? Being a coder I understand the C#, but unity - specific elements are a mystery to me. Some more in-depth narrative would help a lot!
@@Jimbeksus Check out the basics playlist which will help you get familiar with the basic elements of Unity like Game Objects, Sprites, etc ua-cam.com/play/PLzDRvYVwl53vxdAPq8OznBAdjf0eeiipThttps.html://ua-cam.com/play/PLzDRvYVwl53vxdAPq8OznBAdjf0eeiipT.html
A Sprite in Unity is essentially a texture with some extra options, check the import options for any texture in your project files and you'll see the Pixels Per Unit. Thats how many Pixels of the texture should fit in 1 Unit in the game world.
forsome reason the background goes backwards not forward
For me, the code shown in the video doesn't work for creating the vertical infinite.
However, it does work for the X axis, and I also can move for the Y axis, except that for the Y axis, it is not infinite... too bad. Here is my code:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class ParallaxBackground : MonoBehaviour
{
[SerializeField] private Vector2 parallaxEffectMultiplier;
private Transform cameraTransform;
private Vector3 lastCameraPosition;
private float textureUnitSizeX;
private float textureUnitSizeY;
private void Start()
{
cameraTransform = Camera.main.transform;
lastCameraPosition = cameraTransform.position;
Sprite sprite = GetComponent().sprite;
Texture2D texture = sprite.texture;
textureUnitSizeX = texture.width / sprite.pixelsPerUnit;
textureUnitSizeX = texture.height / sprite.pixelsPerUnit;
}
private void FixedUpdate()
{
Vector3 deltaMovement = cameraTransform.position - lastCameraPosition;
transform.position += new Vector3(deltaMovement.x * parallaxEffectMultiplier.x, deltaMovement.y * parallaxEffectMultiplier.y);
lastCameraPosition = cameraTransform.position;
if (Mathf.Abs(cameraTransform.position.x - transform.position.x) >= textureUnitSizeX)
{
float offsetPositionX = (cameraTransform.position.x - transform.position.x) % textureUnitSizeX;
transform.position = new Vector3(cameraTransform.position.x + offsetPositionX, transform.position.y);
}
/*
if (Mathf.Abs(cameraTransform.position.y - transform.position.y) >= textureUnitSizeY)
{
float offsetPositionY = (cameraTransform.position.y - transform.position.y) % textureUnitSizeY;
transform.position = new Vector3(transform.position.x, cameraTransform.position.y + offsetPositionY);
}*/
}
}
You typed x twice instead of y...
private void Start()
{
cameraTransform = Camera.main.transform;
lastCameraPosition = cameraTransform.position;
Sprite sprite = GetComponent().sprite;
Texture2D texture = sprite.texture;
textureUnitSizeX = texture.width / sprite.pixelsPerUnit;
textureUnitSize = texture.height / sprite.pixelsPerUnit;
⬅️
}
your a hero brother 💪💪💪💪💪💪💪
i love it !
I had a 2.5D game, with3D characters, platforms and objects etc on Z=0. Imagine Little Big Planet. I need to set up an infinite scrolling background like this, but it only seems to work when the sprites are on Z=0, which obviously intersect with my game objects. Is this technique strictly ONLY for completely flat 2D sprite based games? Thanks.
If your camera is 3D then you don't need this since you have Parallax by default, just place your backgrounds at different Z positions.
The further an object is from the camera the slower it will appear to move.
@@CodeMonkeyUnity Yes, I understand that, but to get the kind of of parallax you demonstrate in your tutorial, the horizon layer will have to be really far away on the Z, and a huge image. Is there not a performance hit if images are hugs, or scaled up?
Thanks.
Thanks, you are the best
I know it's a long shot because of the age of the video, but with the [SerializedField] I am getting an error in unity that says "the type or namespace name "SerializedField" could not be found" am I doing anything incorrect?
It's SerializeField
hello, is it work for the Main camera by orthographic ??