How to Implement Player Movement with Rigidbody in Unity
Zenva
ACCESS the FULL COURSE here: https://academy.zenva.com/product/rpg-academy/?zva_src=youtube-rpg-academy
TRANSCRIPT
Hey guys, welcome back. In this lesson we're gonna get our player moving around the level based on our inputs. We're gonna be able to hit the W, A, S and D keys, the arrow keys, or even use a controller's analog sticks to move our player around. Unity makes it very simple to use all three of these different types of input without having to worry about each individual one. So we're gonna move the player around, we're gonna calculate the movement based on our input, like I said, and we're gonna be colliding with objects like the walls, the enemies, and the coins using our collisions with Rigidbodies. We'll talk about exactly what that is here in just a second. So back in Unity, the first thing I wanna do is I wanna go to my scripts folder and I wanna right click and I wanna create a new C Sharp script that's gonna be called player. This is gonna handle everything our player does. Now, as we know, all I have to do is go to my player object, drag my player script file directly onto my player object, and now anything we write, we can actually talk to this object and talk to the components on this object. But the important thing we're gonna using for this is what's called a Rigidbody.
Now outside of physics, all we have to understand is this allows us to be physically enabled, so we can apply gravity, we can apply collisions and force and all those things you get to do in real life, right? If you pick up your phone and you throw it across the room, you applied force to it and then it's gonna collide with the floor and then it's going to stop. Stop moving, right? So we can do that with these objects by using something called a Rigidbody. So I'm gonna add a component. I'm wanna add a component called Rigidbody. Not the 2D version. Make sure you have the regular version. And now this gives us some physical components, some physical attributes, but all I care about for this is gonna be the mass of the object, so how heavy is this object? And we'll tweak this as we go when we add jumping and stuff. And also the fact that we are using gravity, so we're going to be applying a downward force to this object. Now with this setup matched with a Box Collider here, whatever kind of collider you have, we should be able to physically interact with our world. So let's test this out. What I can do, just to play around with this, is I can just grab my player. I'll drag him into the sky here. And now if I were to click play, what we should see is our player falling to the ground. That's pretty cool, right?
So if I were to grab the player again while it's simulating, I can drag it up, and it'll fall to the ground. And that's what we're gonna do to work with ... https://www.youtube.com/watch?v=4Qq7d9elXNA
46778361 Bytes