Trajectory Line in Unity (This ain't your mothers trajectory line)
Vložit
- čas přidán 13. 09. 2024
- Trajectory prediction lines are everywhere in puzzle games and you even see them in action games to simulate grenade throw arcs etc.
This is a new method recently made possible with the addition of Multi-Scene Physics. We now have the ability to simulate frames into the future using the in-built physics system, taking into account the physics material of each object and even external forces like 2D force effectors... Making this significantly more powerful than your mothers trajectory line.
Scripts and assets: github.com/Mat...
❤️ Become a Tarobro on Patreon: / tarodev
=========
🔔 SUBSCRIBE: bit.ly/3eqG1Z6
🗨️ DISCORD: / discord
✅ MORE TUTORIALS: / tarodev
I somehow sped this entire video up and didn't even realize Sorry about that!
😂
😂
I knew it !
I usually watch tutorials at 2x-4x speed soooo meh
really? this was the first video i've ever seen from you, and I was actually enjoying how you go straight to the point, and how you don't waste time, and are going in a pleasant speed.
Hey! Cool tutorial but unfortunately it's not very performant. In your sample scene, enabling the trajectory line drops the framerate from - on my computer - a solid 60fps to about 26fps, and increases the render thread by 10 times (~0.8ms to ~9.7ms). I think the problem might be using Instantiate and Destroy on every frame. To anyone watching this and wanting to implement it, you might want to consider a slightly tweaked approach!
Yup, it certainly takes a toll. I've thought about it a little bit since this release and there are a few things to look into:
*Reducing iterations. Increasing launch velocity can increase the length of the trajectory line, but may not be what you want
*Object pooling (as you mentioned about the instantiation)
*Reducing physics step time
*Using a 'debounce' strategy where as the user is interacting only a fraction of iterations are calculated, lerping towards Max iterations as the player stops input. This is good because the first bounce is usually the most vital so they can line it up without lag and simply wait a second for the full line to be calculated. Not perfect..
Keen to hear other ideas
@@Tarodev I've done a similar implementation in 2D, and instead of instantiating and destroying the ghost ball, I just set its position back to the cannon before doing the physics steps. Works nicely! Thanks again for the hard work put into the tutorial.
@@GMTK I'll pin this thread so others can benefit from your discovery.
Great video and concept! Much easier way of physics prediction than the mathy alternatives. It does come with some performance challenges, but nothing that (probably) can't be solved with a little work. Thanks for making this!!
"Object pooling" is the key there, as you don't want to be instantiating things every frame.
I'm blown away that u can create another scene inside a scene.. Never used them before
Agreed, this was the most magical part to me. The fact that he instantiated a scene that laid over the existing scene, then got ahold of the "PhysicsScene" on that and called "Simulate". 🤪 Very magical indeed.
this is easily becoming one of my favorite gamedev channel of all time, i really love your teaching style man.
btw, mot sure if you're familiar with it, but Compute Shader (not just "shaders") is one of the rarest topic out there for unity, if you can get into it, that would be a blast!
I've watched Sebastian using compute shaders and it looks amazing! I do plan to venture in at some stage. I'm glad you're enjoying the content
Thank you! For someone who's not good at programming, it's really helpful that you've uploaded the scripts!
Happy to help! Keep in mind, this method can be quite CPU intensive
Great video. I think these kinds of videos would be even better if you have a brief high-level overview at the start to give context to *why* you’re doing things like creating a dynamic physics scene.
You're right. Hopefully as you continued watching it became apparent? But yeah, I shouldn't make it seem like a mystery.
That is very clever. I just wrote a script to calculate trajectory lines for a 2D game using circle casts and vector math. It works fantastically and I'm glad to have done it, but I think I'm going to switch to this method. Never thought of using scenes like this, especially for manually controlling physics steps. Thanks a ton :)
Just a word of warning: your method will be insanely more performant. This method is calculating n physics frame every frame, so it can be very heavy. Download the package I provided, plop it into the scene and experiment before swapping over
@@Tarodev Ah okay, was thinking about that. Appreciate the heads up.
can you help me with that script that you wrote? i'm trying to do the same but it doesn´t work
3:57 "... and this will take in my ball"
I hope this channel uploads more game development tutorial videos like brackeys, because I really like your previous tutorial videos.
More coming, stay tuned 😊
Thanks so much!!!
I was literally dreading having to create a Trajectory Prediction method today, until this!!! GENIUS!!
Just be aware, it can be quite expensive. Try to keep iterations as low as possible and you should be fine
I love how you think about something and come back :D
Great basis for a trajectory line. However as other commenters have mentioned, it's not the most optimized thing. So to improve it I put the ball back to the start position instead of deleting it (this greatly decreases the chance for ram to have small gaps). I also only call the simulate when the barrel has moved since there is no reason to simulate the same trajectory every frame if it hasn't changed. If others are interested then I will provide the code. Otherwise great video it taught me a lot.
Hi! I'm interested in the code. I want to know how others are doing it since object pooling is not helping. I'll be grateful if you would kindly provide the code!
would be interested in seeing the code as well
Could you share your code? It's very interesting to see your solution.
@@mrcyruscrap This is so long ago lmao. I don't have the source code anymore unfortunately.
Excellent tutorial! Thanks for sharing
So easy and helpful. Thanks!
You make really good videos. I love the production and work on your videos.
Very clean approach and thanks for the tip it's very usefull
I know this is kinda stupid, but I can't help but laugh every time you mention "BALLS"
Oh baby
Excellent tutorial again.
thanks! this is exactly what I need for client-side prediction for my plane sim
Love that, I have done simulations of this where it would lag the level but this was something I only recently tried.
Thanks for the great content as always sir.
So this question comes up a lot in gamedev! I've linked this tut in various discords each time the question appears.
You know you found the right tutorial when it has way less views than it should and gets right to the point about exactly what you want. Everyone sleeps on the best tuts.
Thanks, great tutorial. Really saved me! :)
Another great totorial
Oh very nice tutorial I can see myself using this and improving it as I go
Btw that materials shaders so Cool do you have tutorial on those? Very pretty colors wow
Not yet, but I plan on making a video soon on my scene setups!
i think you can create a physics tag (ghost) which only affect (obstacles) so by doing that you dont need to create another scene -- i just thought of that idea after your video i was doing it mathmatically before -- so thanks soo much for the smart idea
0:32, do you mind making your way into my brain? That shook me 😂
This is incredible. Cheers.
Great video! However, here's few things I'd change:
For the end tip, instead of updating the object's position every single frame, for every items in the dictionary (which is goddamn expensive and is not a good habit to have if you're planning to release a game that's not essentially destinated to high end pcs), I'd have a threshold variable that's representing how much of a difference of position and rotation requires a change. Then I'd check if the position of the ghost object is approximatively the same as the position of the real object. If not, then change it's position. Like that, you would avoid having useless calls in the update method, which is a method you should really be careful with.
Also, like for the previous advice, trajectory predictions like you've shown in your video is great and always 100% accurate. However, it also is very very performance heavy, and runs at less than 60 FPS on a middle-end laptop. Something I would change to increase performances would be to actually check any changes of position or rotation in the scene, regarding the concerned objects (the canon and the ghost obstacles), and only calculate a new trajectory if the objects have changed.
Hello! i implemented this in my project, but i dont get why it isnt working, seems like the problem is when i apply the force to my object, because the position remain the same, even if in the main scene it moves correctly. I dont know if thats becase i made the same but for 2D physics.
wow nice tut man :3 thanks
Great, helpful video, thanks ☺
Very informative video thank you.
😊
The playback speed of this video is a bit disturbing, I don't think it's necesary to speed it up in post as we can set the playback speed on youtube if we need to
This was a silly mistake and I hate it :( I must have somehow sped the entire thing up when it was only meant for a single component. Didn't even notice until somebody else pointed it out a few months back
@@Tarodev ah fair enough, I just set the playback speed to .75 which did the job. Just found your channel yesterday, awesome content, appreciate the work you're putting into it!
Hello, I recently tried out something similar and would urge anyone with complex scenes to instead duplicate the OBJECT that moves instead of the whole SCENE, and then manually call FixedUpdate() on that cloned object the hundreds of times you need. More complicated than it sounds and not a one-size fits all projects solution but hope this comment helps someone.
Personally I came here for the line shader 😃
How would you do that? Do you have more of an example?
you deserve 1M Subs
That's a lot of subs 😛
I love it thank you!! But I am more impressed than my mothers slipper trajectory
They're like snipers with those things
@@Tarodev 💯🤣
So the 2nd scene is time traveling to see what's going to happen :o
That's a good way to put it. Pretty cool 😎
Another great video from you. Thanks. Keep up the fantastic work.
Would using jobs and burst compliler mitigate the performance issues?
Thank you for tNice tutorials, tNice tutorials was a huge help.
Interesting technique, I didn't know you could do physics scenes! It would be nice to also get rid of the renderers and other components of all the objects instead of disabling them, as they are just worthless information in the memory. The example you use is simple, but on complicated gameobjects it might make more sense to create a blank gameobject as ghost and copy to it only the relevant physics components instead of instantiating a clone. This would also save you from having to modify all your code with ghost checks and have it coupled with the trajectories system.
Another thing is that keeping track of only the static objects would cause problems if you later did other modifications to the objects such as changing the physics materials on a static object.
Hi @Tarodev. What are you using for the 3d models in your examples? is it specific shaders? or preset that you imported from the unity assets store? thanks
Awesome video! What would mamas trajectory be like tho?
It's too high level for me. It's mind boggling how someone can come up with all of these solutions from the scratch I can barely follow the tutorial. I bet I wouldn't be able to come up a solution by my self from the scratch even after 20 years lol. I got spoiled by papa Brackeys simple tutorials so much
Don't say that brother. In 20 years you'll be making your own game engine ;)
For some people things like code, math, physics, is like nerd-p0rn. Different strokes for different folks, I guess.
I wouldn't sweat it. I suck at design. So maybe you're better at other things like design, or writing, etc.
Good luck
@@Tropicaya Very true, I've been learning the coding part of game dev for a better part of a year and it's definitely my favorite part, but I still have no idea how to make a game "fun" 😭
Thanks
Great! Can you please share full unity proeject please. Will help for beginners like me :)
Might I ask how you had it define the field for you with whatever keybind you hit twice?
Your tutorials are really awesome. Can u make tutorial about stack color game?
That sounds like it could be a good idea. I'll add it to the list 😊
my question would be isnt it more heavy to create a second scene just for simulation instead of using math for bigger scenes ? assuming you dont need the bounces ? the speed up isnt an issue still good to follow tutorial 10/10
thank you
You created a new scene, so the physics can only be calculated for objects that are part of the scene?
What if, instead you used the defaultScene's PhysicsScene, it would still work but it wouldn't be efficient? Also it would move the real objects with Rigidbody which we don't want I guess?
That's pretty much it, yeah. We could do it on this example if it wasn't for the breakable boxes which I didn't include in the simulation scene. You'd have a phantom ball smashing the boxes the moment the trajectory line hits them :P
Thx bro so much
awsome tutorial sir
Thanks pal
@@Tarodev i am working on 2d scene if stuck could you please help ? ☺️
@@rathodketan5551 what's the problem?
@@Tarodev in 2d scene line renderer not showing 😞😓
GREAT!!
Or, you could update the position only right before the trajectory is to be simulated, I like to keep Update() as a last resort
Hi! thanks for the tutorial. I'm just getting into physics scenes but i wonder why you didn't use Physics.autoSimulation = false (true)? Thanks.
thx
Great tutorial - is there any way to stretch out the prediction for a longer time without slowing down framerate? I'd be happy if I could do it at the sacrifice of line position draws but I can't seem to have any success extending the prediction before I hit framerate issues
I haven't tried this, but maybe double the time step each iteration? I actually don't know how it works under the hood though and chances are it's calculating every step regardless, but try that.
Any accurate way to use less iterations that cover a longer timespan, for efficiency?
Maybe not because the gravity in my scene changes depending on position.
Edit: I ended up using a maths method
if i want to spawn only 3 balls and then stop??
Works well but very intensive so I can't run it every frame (I have a solar system and apply real time acceleration every frame. So simulating several seconds of that every frame is a lot)
I guess I'll have a button you press manually to run the simulation
1:10 Is there a shortcut to make global variables autocomplete? I wonder!
Alt + Enter. If it doesn't work it's probably a ReSharper feature. Rider also has it built in
Another great video, thanks! I'm wondering: Any way to draw the line until it collides with a surface? Or to say until it collides up to a fixed amount, like 2-3 times? (Instead of X number of frames)
Since the physics are calculated, I can only imagine that collision events are enabled as well, so if the ghost ball has an onCollision method, that just adds to an int whenever it collides with something, that the for loop that adds positions to the line renderer can use, you can just break the loop whenever that number is 1.
That does depend on how the onCollision method works in the simulated physics scene though.
Isn't this duplicate scene a memory hog? this scene is simple so it's cool, but what if i have an enormous terrain, or some complex colliders, some object with a gorillion tris, or whatever? is it viable?
It's not so much the double colliders, but the huge amount of physics steps being calculated every frame.
You can perform trajectory calculations using simple math, but it doesn't take into account physics materials or effectors. It can also get complex if you want to simulate the bounces...
So really it's a pros and cons kind of deal. But this technique is by no means performant. Cool though 😎
Hi there
I love this tutorial but when I tested under a more demanding project where I needed lots of plot points, my engine began to choke. How can I best manipulate plot spacing?
thanks. but how can we iterate through Transform ? on line 23 in foreach loop we need array or list. How it is possible?
Is there any way to make line renderer length limit ?
line renderer endPos follow mouse position but line length goes infinite want line length limited.
can you make the trajection stop at the first collision? i've been trying to do that but i can't seem to figure out how.
if (Physics.OverlapSphere(ghostObj.transform.position, 2, LayerMask.NameToLayer("Body")).Length > 0)
{
lineRenderer.positionCount = i;
break;
}
I use this, it uses a layermask for the layer collision. I think it works
Edit: It's placed in the for loop for the physics iterations
WHAT IS THE LINE MAT?
also my line is too small. what should i increase?
The velocity of my spawned objects does not change :(
in mine the line doesn't appears, what can i do?
this is awesome, but is there any way to optimize it for mobile?
Whats the point of using _ before variable names ? Thanks for tutorial
It's just by naming convention and used to indicate that it's an instance variable of the class. It's not needed, and I personally don't use them as I'm used to Java conventions.
bro can u make tutorial turn base game in unity ?
I 'kind' of cover that in my grid series (in part 2): czcams.com/video/kkAjpQAM-jE/video.html
But maybe I could do a more in depth one to cover all the bases...
I want to start making soft as a hobby , but everytNice tutorialng is so overwhelming and I still feel lost when attempting to make soft.
lmao "this aint your mothers trajectory line"
Can't we just shoot something invisible with same characteristics and get it's route?
This technique predicts the future. But yes, if your scene doesn't change that should be fine.
My foreach is not copying the children. What am I doing wrong?
Edit : Nevermind, I assigned the wrong object 🤦♂️
This seems very inefficient, I guess it's kinda... a fun art project. I wouldn't put this in my game even if i needed to calculate bounces(I don't really lol), I'd just take the effort to do the super complex math. It's not worth essentially doubling your game's physics load for a trajectory line lol
100%. Although, if you're able to use it lightly in a game which has no other load, it should be fine. Absolutely smashes your system though :D
Besides projection, this video introduces you to the concept of multiple physics scenes. How handy is that? No idea
@@Tarodev lol, nice. I suppose it'd be fine for a game where each scene doesn't have too much content. But since becoming a programmer, I've become super picky with optimization lol
@@fukukyun78 that's a good way to be. Just don't let it get in the way of actually finishing projects 😉
the scripts and assets link is broken. plz fix it I can't download :(
I updated it with a direct github link
Lmao that caption
Why did you speed up this video?)
This was a DUMB editing mistake. I noticed after uploading it... It was only meant to speed up one section, so don't ask me how I managed it.
Anyone knows how to destroy created scene gameobject? Please help 🙂
Why do you make things complicated?..Why use create scene and put objects in.?
If you can show me a simpler way to handle a full physics simulation (including physics materials of each object), I'd love to see it! Always keen to learn.
Could you not just do this with some simple math and some logic getting the normal of the surface that each arc hits?
안아줘요
this looks like a super fun mechanic to play with! now I want to go off and make a wacky mini golf game.. 🏌️