Camera-Relative Movement in Unity 3D Explained
Вставка
- Опубліковано 10 лип 2024
- What the heck does all this code mean?! Today we’ll break down every line so that you can move your characters relative to the camera’s rotation in Unity 3D! Learn the basics of Vectors and SPACE and how to transform between the two. Put your programming hat on and let’s get started!
ACCESS PROJECT FILES & SUPPORT THE CHANNEL:
💛 / iheartgamedev
iHeartGameDev Merch:
💛 www.iheartgamedev.com
WANT MORE?
Check out previous videos in this growing series of tutorials:
✅ • Character Controllers
✦ Like the vid? Please consider Subscribing!
bit.ly/2YdIb6j
SOCIAL:
✦ Discord
/ discord
✦ Twitter
/ iheartgamedev
LINKS FROM THE VIDEO:
🤖 Download Jammo for YOUR game:
assetstore.unity.com/packages...
⭐ And Check Out @Mix and Jam !
/ mixandjam
►TIMESTAMPS:
Intro: 0:00
Camera Relative Overview: 0:32
What are Vectors: 1:32
Vector3s Explained: 2:08
Directional Unit Vectors: 2:56
First Code Breakdown: 3:52
Moving GameObjects: 4:47
Coordinate Spaces Explained: 5:34
Moving Gameobjects in Space: 8:58
Second Code Breakdown: 9:50
Rotating Vectors Explained: 10:23
Rotating Vectors Example: 12:00
Moving in World and Local Space: 14:05
Removing Y Value to Stay Grounded: 15:30
Last Recap: 16:55
Final Words: 17:56
The incredible work that went into visualizing this is awesome. Stuff like this is truly what helps developers like me comprehend the logic of what’s happening. Thanks man!
Thanks so much, Jadon! The kind words and appreciation for the time that goes into the video mean a lot and make it worth it! Hope it helps!
@@iHeartGameDev Your hard work paid off. As someone who works in the training space in a different field, this was an excellent way of breaking down a seemingly abstract concept and I'll be adopting some of these methods for visualizing my own trainings I provide. Excellent job!
Heyyyyy, look at that line work! Well done Nicky, amazing stuff.
EDIT: Damn. Although this video is about camera-based movement, new devs could come here to get a really solid understanding of vectors. You've outdone yourself on this one.
Much love for the kindness, my friend! I had to learn all about Vector's and Coordinate Spaces to understand the code we're writing for the camera-based movement. That just tells me that everyone else should too XD
Welcome back to a brand new video! Super excited to finally share this with all of you and I hope this helps you on your gamedev journeys 🍻
One point of clarity that one of the awesome patrons pointed out on the early access video: towards the end of the tutorial, we use InverseTransformVector which is affected by scale. We can alternatively use InverseTransformDirection which is not. Shoutout to vantreeseba for the helpful info!
Thank you all for the support and hope to share more with you soon!
You summarized my 3 month study in a 19 minute video. You are awesome !
Hahaha this is one of my favorite comments I’ve ever received. Thank you for the kind words!
Man, I wish I had this tutorial back when I had started working in unity. It took me a long time to get to grips with how this worked and even now i'm still learning things from this. For instance I never noticed my character slow down without normalizing the vectors on the camera transform and i've heard absolutely no one mention it when going over that part of the process (at least in terms I understood lol) so seeing it broken down and illustrated really helped give me a better understanding.
Thanks! I hope that you still learned something, or at least reaffirmed what you already know from watching the video! And hopefully it helps some newer devs out :)
I followed your character controller tutorials and this issue was a literal abyss, coulnd't have figured it out on my own, finally can continue working on my project :D
It’s so funny because I went through your other tutorials and I was realizing that it wasn’t exactly what I looking for, and then I found this video and it was like a gift from the gods. Thanks!
i'm going to cry, i've been learning unity for almost 5 years in my free time, trying to get that game realese and never anyone have teach me unity this way!!! :') thank you so much! i feel that game dev heart in each one of your words and explanations. I just want to say THANK YOU. this is the only kind of tutorials that really deserves attention, being that doesn't distracts or take for granted the lines of code! Congratulations and i will be a loyal sub for now on!!!!! 😭😭😭
Wish I had this 10 years ago, you don't need me to say this, but this is and incredibly well made way to help people deeply understand concepts. What an incredible job!
Amazing work, thanks for taking the time to visualizing this. This will help dev understandings
Another great in depth tutorial with the same incredible quality you provide. Love it!
Hey! The Wight One! Thanks for stopping by again 😊 and for the kind words
Every new overview of applied vector math helps it stick in my head just a little bit better. Thanks for that :)
Happy to help!
Amazing video! Not only did you provide the code, you also explained in details how it works!
Keep it up and thank you so much :)
Thanks for watching Yair!
Such a nice explanation and editing. I don't have words to appreciate this content. Thank you once again 🙏
Hey Ritansh! I’m glad you liked it! I hope it helps!!
Great job and great video editing as always. Very good job!
What a fantastic explanation with great visuals to, thanks!
this is hands down the best vectors tutorial/explanation ive ever seen
Thank you!! Hope it helps!!
This video is just incredible, thank you!
Awesome video once again. I just found your channel and I already learned so much!!
So a big Thaaaank youuuu, to you!!
This series is gold ❤️❤️❤️❤️
I'm so hyped for every video from this channel. best unity channel in the world.
Thank you so much Alde! I really appreciate the kind remark! Hope I can continue to live up to the praise.
Hey man, so good to see another video from you
Thank you KnObi1! :D
This is awesome, this channel is amazing, I've learned so much thanks to you, please keep it up !!
Thanks so much Scarecrow! Happy to hear that my videos have helped
Amazingly detail video.
You really are amazing
It's about time!!!!
:) Thanks!
Thank you for the patience!! Hope it helps!
@@iHeartGameDev Oh. I was talking about someone finally putting out an awesome camera tutorial! Love the detail you give in your videos!
Great work! Thank you!
Wow, you outdid yourself this time with that editing and visualizations. Keep them coming!
Much appreciated, my friend! Fun fact: 90% of this video was made in Blender! Thanks as always for watching!
@@iHeartGameDev Wait. which sections of the video are the 90% in question?
@@laur429 I’ll never tell!
Thanks! Nice tutorial
Maybe you've learned something, maybe you don't. But in the end, this kind of content, freely available, is a friendly reminder of how much the internet is incredible.
Super amazing content man
Just found out your channel whole searching for Animation in Unity. And I loved that series and your other videos as well. Keep making such content.
I would like to know that how Inside's player movement works with relative to camera movement🤔
Can u plzz make a tutorial on it?
thank you so much, it helps a lot
Simply brilliant
writing this so i see it if i ever have to comprehend this again. you're multiplying the z/x of the measured point from wherever you're looking, and multiplying that times the actual axis you're moving on as oriented and measured against the world.
This did a good job of explaining C#! I had to join the discord
Great video, really liked the animations.
Just a little remark: if the camera is also rotated around the z axis, the forward and right vectors are no longer perpendicular once you set y to 0. So the resulting input vector will be a bit skewed.
Great explanation!
Thank you Mark! Hope it helps! :)
every beginner unity devs has to watch this video
Agreed!
awesome work
Best explanation thanks alot!
THANK YOU SO MUCH THIS TOOK ME WAY TOO LONG TO FIGURE OUT 😭
You blow my mind ! 💟
Brilliant explanation, although I'll have to watch this a few times!
Omg!! Tysm 💜💜💜
Which VS Code theme are you using
I used this logic in a game where I add a physics force to a ball in a game that's constantly rotating, but didn't want the camera to alter the movement of the ball. I got the forward and right of the camera, and had the camera point to an empty object attached to the ball(the empty object tracked the position, but not rotation of the ball). Then I used the empty object info. to apply force to the ball. Used cinemachine to deal with the camera rotation around the ball (actually it was pointed at the empty game object, so i could move it a bit as I wanted to offset the camera target angle). This way I could use w,a,s,d for movement and mouse for camera movement. Not sure if it was the best way to deal with it, but it worked pretty good.
This video helped a ton.
Fantastic explanation! Thank you for sharing Darin!!
@@iHeartGameDev Thanks. I've been trying to learn ways to reuse code and during this I was able to move the script that I had on the camera to the empty object for tracking an object, but not the rotation.
Yo I made it on the video! Best tutorial I've seen hands down.
:D heck yea! Thanks Dahstroyer!
Dude. Literally just spent 4 days setting up a player controller with a free look camera pretty much from scratch for this exact result. Was looking for a Smite style cam if you're familiar with the game...
Great vidéo for sure, thanks a lot ! But i tried to emplement the code in my game and can't figure how to do it... is the script have to be in the camera or the character ? and does this code allow the character to move when we press the arrow / WASD keys ?
My English is bad, but I learned more from this video than from my native language videos. Incredible.
DUDE, how the heck are these videos made? After Effects? The animations are so precise! whats......
I made this one 90% in Blender
Actually solved alot of my problems and dumbed it down to my level of understanding, really amazing work, this is quite literally the only roadblock i've ran into while making my game. Now I do have 2 questions, 1: does this work with cine Machine? and 2:Does this work with the new Input system?
Top Notch presentation and tutorial, I've shared this with my team
If Im doing it now, Im sure someone else is: if you watched his state machine video, you just gotta apply the code to the walking state/running state, and alter it a bit; you won't need the "playerVerticalInput" / "playerHorizontalInput" since your statemachine should already have those values with the input machine, forwardRelative input variables will need Ctx.CurrentMovementInput.x and .y respectively instead, and Ctx.appliedMovement will have to = cameraRealtiveMovement * your speed value.
Oh and I didnt make it a seperate function I just put it in the UpdateState function... Im sure theres a better way or something but its working for me so meh also be sure to zero out the y functions or your character will fly in 3d space.
Awesome video
Thanks for watching Marek!
fantastic 🎉🎉🎉
Thank you so much!
so how do i make my movement corespond to direction that my camera is facing so that pressing w moves me foward even tho it applyesforce in the oppasite dirrection or do i have to scrap my movement sorry for bad english
I never thought about, or maybe I keep forgetting, that you can think of this as coordinate space conversion. It does sometimes help to see it as a change in coordinate space, though you usually care more about the local change until you convert to world space or whatever other space you're converting to. I find it really odd that you can sort of rotate in that way. But then, I guess, that's probably how matrix math works. I gotta train my brain to think in terms or changing coordinate spaces rather than translations and rotations of a single object.
EDIT: In the same way it's pretty obvious that the world revolves around the camera, but it's difficult to see in those terms since we are conditioned to see things in world space.
EDIT 2: Unfortunately this wasn't what I was looking for, but it's interesting and something to think about.
I used the project method to project my cameras directions on to a plane that its normal is the players up wards vector, idk if that way is better or worse, nice vid
I’d love to learn more about this method. Is there any resources you have to share where I can learn more?
@@iHeartGameDev Vector3 forwardDirection=Vector3.ProjectOnPlane(Camera.main.transform.forward,ctx.gameObject.transform.up);
Vector3 rightDirection = Vector3.ProjectOnPlane(Camera.main.transform.right, ctx.gameObject.transform.up);
this is how I get the directions which I don't think makes any difference, and the (ctx.gameObject) is the player, I used your state machine :3
@@siavashaliyari8567 Super interesting! I've never seen ProjectOnPlane before. I'll have to play around with it! Thank you for sharing Siavash!
Hi! Works great for camera controlls but may I ask why does it decrease the gravity effect? the character falls incredibely slow and idk why, but by removing this code gravity works well. Any tips?
thank you!
The only thing I would add to this code is literally the last line
public float speed;
this.transform.Translate (CameraVariable * speed * Time.deltaTime)
Cause my character was zinging all over the world!
Hi! My character is also zinging, could you explain a bit in detail what led you to this solution? :3
id love to see this with the new input system, having issues figuring it out
Which video editor do you use?
hello am not sure if this has happene to someone but my unity editor keeps telling me that am using the new input system not the input package which am confuse dhow you did it pls can you help me
How do I actually implement this?
I added this code to the movement code from the earlier tutorials (with the new movement system),
called it in void update, and it does seemingly nothing.
Do I have to multiply my movement with "cameraRelativeMovement" somewhere?
Hello! Thank you for the video! Really great content, was able to implement changes i needed
I wanted to ask about movement code. My computation handling of adding velocity or rotating is all in the update function. I feel like it would be better if there are individual functions for it to make it easier to read (maybe even better performance since it doesnt really run every computation at every frame). Although im scratching at my head on deciding where to start or how
Please let me know what you think would be best
Where do i put the code? PlayerController script or CameraController? Because I am using roll-a-ball tutorial movement script, i don't know where to place your script (I just started unity so I'm a noob). I am using cinemachine for my mouse inputs if that's going to effect anything.
Where do we put this in the code from the previous videos in the series? I wrote the function in the body of the PlayerStateMachine. Do I just call the function in update() after doing that? When I run the code with the MovePlayerRelativeToCamera() function in the update, my character speeds forward and the camera does not adjust to his movement. Any help would be appreciated!
Hey! There’s a separate video explaining that right after this! Check the channels list of videos
@@iHeartGameDev Great, I'll check that out! thank you so much for the reply!
This tutorial is awesome. You are gonna replace "brackeys" youtube channel.
Thanks for the kind words!
How do you change speed?
One thing I have had trouble with in the past applying this method, is that if you have the camera following the player it can lead to highly unwanted behavior - for instance, rapid spinning in place of the character.
Otherwise, do appreciate the logic breakdown at the start. Allows those who understand the math get straight to the point.
How do you fix this?
Great video, one movement method you forget is to keep the player always on Vector3.zero, and then moving and rotation the whole world around it.
how can I get camera relative movement using the new input system?
Fantastic video BTW!
i just want to ask, where should I write this code to connect with jammo
stay tuned! New video really soon showing how to!
Could your make a tutorial about behavior trees pls
Will you be covering cinemachine?
Next video will break down Cinemachine's Free Look Camera!
Think i'll need to watch a few more times
That’s like me with Freya’s video 😂 A LOT to take in here in a short amount of time
@@iHeartGameDev XD
Loving the content man, always high quality stuff
Another question.. what is considered "Horizontal" and "Vertical"? Left/right, forward/back on a joystick?
Hi, how to calculate distance traveled from camera movement ?!!
How would this be implemented in the current state machine system?
Coming after the next video’
I'm confused. How to connect this to a speed variable also forward and backwards movement isn't working.
i followed your character controller tutorial, but when i do this I can't apply the gravity. ¿What can i do?
Awesome! Thanks for watching! My next video will show you how to do it!!
Nice video, works fine for me, but the only issue, is my person wont turn to the foward direction :(
can anyobdy send the final script ?
My Character runs in a Circle, when moving sideways. What could be the Problem? It should go in a straight Line.
Your tutorials have been a huge help, and I'm amazed this came out literally the day before I needed it hahah
I'm having a bit of an issue though. I'm trying to get this to work with a character controller and the new input system, but I'm getting an issue where moving the camera after the character has started moving doesn't change the character's direction. I can, however, stop moving, reposition the camera, and the character will move relative to that new position.
Any ideas what might be going on?
Hey! It sounds like values of the camera forward and right vectors aren’t updating for some reason if you’re moving - or they aren’t being used in your movement code at that point. Definitely worth investigating the vector values being passed to your movement method
@@iHeartGameDev I kind of had to shove the code into the onMovementInput method, otherwise it just won't respond at all. Right now, this is what I have there:
//get player input values
currentMovementInput = context.ReadValue();
//get camera-normalized directional vectors
Vector3 forward = cam.transform.forward;
Vector3 right = cam.transform.right;
forward.y = 0;
right.y = 0;
forward = forward.normalized;
right = right.normalized;
//create direction-relative input vectors
Vector3 forwardRelativeVerticalInput = currentMovementInput.y * forward;
Vector3 rightRelativeVerticalInput = currentMovementInput.x * right;
//create camera-relative movement
Vector3 cameraRelativeMovement = forwardRelativeVerticalInput + rightRelativeVerticalInput;
//Apply relative movement to current movement direction.
currentMovement.x = cameraRelativeMovement.x;
currentMovement.z = cameraRelativeMovement.z;
currentRunMovement.x = cameraRelativeMovement.x * runMultiplier;
currentRunMovement.z = cameraRelativeMovement.z * runMultiplier;
isMovementPressed = currentMovementInput.x != 0 || currentMovementInput.y != 0;
And I just can't figure out how to go from there. Separating them into separate methods just causes the local cameraRelativeMovement to be unusable in onMovementInput. Declaring cameraRelativeMovement in the class and then defining it in the method also breaks it. It just REALLY doesn't want to be anywhere but onMovementInput.
@@RinzyOtt is this character controller based on my character controller series?
@@iHeartGameDev Yes! Sorry, I should have mentioned that hahah
@@RinzyOtt You figure it out? I've tried alot of solutions and nothing works, with the new input system as far as I know.
I came looking for copper and i found gold
But what if the player comes too close to the camera?
Long way from DirectX days. Does anyone know of a cheat sheet for things typically done in a game with Unity? I.e. I'm guessing the above is cross product or dot product (don't remember which is which). I'd prefer Unity game focus, not jumping into a bunch of math that maybe Unity will do for you.
Waiting...
Hi
head blown
Incredible video . But the background music 🎶🎶 is annoying
Did you really go through ALL OF THAT and not include rotation?
code has 31 errors.
Meow