After Setting Velocity to Zero How to Move Rigidbody Again Unity
Unity: Graphic symbol CONTROLLER vs RIGIDBODY
When you're creating a new project with Unity, one of the beginning things you take to do is lawmaking your avatar'south controller. It's very important and you lot can't rush information technology or your gamefeel will probably exist bad. At that place are a lot of different things to practice, ranging from the inputs acquisition to the movements and feedbacks.
One of the first question I frequently ask myself is : "Should I use a Graphic symbol Controller or a Rigidbody? ".
Today, through the instance of a uncomplicated moving, jumping and dashing avatar, we will explore the two approaches.
Here is a github of the complete project:
https://github.com/valgoun/CharacterController
The Character Controller approach
Setup
Before annihilation let'south just setup the project and a bones examination scene. Equally written in our 8 Essential Gamedev Tips, we must exist organized. Create these folders:
And so create a very simple scene with a ground, a sheathing (our Role player) and a stair to play with.
Adding some verticality with the stairs will allow us to experiment with a lot of different and important things when coding our character: The mode it collides with objects, the gravity when falling from a distance, and besides to test the jumping mechanic if we want one.
The Graphic symbol Controller
The Character Controller is a component you can add to your histrion. Its function is to move the player according to the environment (the colliders).
It doesn't respond nor uses physics in any way.
On pinnacle of that, the Character Controller comes with a Capsule Collider. Before seeing how information technology works, I recommend you to accept a wait at the transmission and the scripting API, it's always a expert affair to do.
For this example, I used the default parameters merely feel free to play with them to sympathize how they work.
The core concept backside the Character Controller is that information technology provides basic collider responses without any physics. Basically, you will move your player like yous would do with a Transform, but you can't go through colliders.
The chief advantage of using this technique is the amount of control nosotros'll have on how your player behaves, but the downfall is that you'll accept to code practically everything.
The Graphic symbol Controller includes 2 methods used to motility the character: SimpleMove and Movement.
SimpleMove takes the speed as parameter and will move the character accordingly. On top of that, the grapheme will reply to gravity. That'southward the simply physic you'll get with the Character Controller. The downside is that the Y centrality velocity is ignored by this method.
Move requires a lilliputian scrap more work simply is less limited. Information technology takes in parameters the absolute motility. Therefore, it's framerate dependent and you lot take to implement gravity on your own.
Fifty-fifty if information technology's the more than complicated method, it's the one I adopt because SimpleMove becomes very quickly limiting by the fact that you accept no effect on the Y centrality velocity.
Basic Movements
Allow's implement a very basic motility. For this, allow's create a new C# script named "Character" that we add to our Player/capsule. Then, we'll need a public variable then we can tweak the speed directly from the editor and a private variable to store a reference to our Character Controller.
(don't forget to get the Grapheme Controller in the First method, see code below)
In the Update function, we go the Inputs, that we and then store into a Vector3. After, we telephone call the Motion method from our CharacterController passing it the Input vector multiplied by the speed and the DeltaTime to be framerate independent and "voilĂ ", nosotros have our basic movements:
Our character moves but doesn't steer according to its movement. It'south easy to change the forward vector of the transform to exist the movement vector:
Gravity
Let'due south add gravity. For that, we'll demand a… gravity variable (or you can use the global gravity with Physics.gravity.y) and individual variable to store the velocity of the graphic symbol.
So, nosotros simply have to add the gravity to our player's velocity at each update and to apply the velocity with the Movement method:
If you try, you volition probably feel the gravity as a bit weird. It's considering fifty-fifty when the player is grounded, the velocity is all the same increasing following the gravity.
To resolve this, we can reset the y velocity to 0 when the player is grounded.
The CharacterController already has a variable to know if the character is grounded simply I found information technology buggy and I tend to make up one's mind myself if the player is grounded. I Like to employ the CheckSphere method from the Physics Class. It returns true if any colliders intersect the sphere divers by the parameters. I like to use an empty gameObject child of my histrion as center of the sphere so I utilize a variable for the radius and the layer. This way I can control in editor the mode I ascertain the grounded status of my grapheme. (If this part seems hard to empathize, take a look at my project and recreate it on yours)
Here, _isGrounded is a bool variable created in the grade, _groundChecker is a reference to the child of the player (the center of the sphere), GroundDistance is the radius of the sphere and Footing is the layer where basis objects are.
Spring
Adding a jump is pretty easy. When the jump push button is pressed and the player grounded, we modify the y velocity. To know which value nosotros choose to set our velocity we tin can use this formula :
"velocity = JumpHeight * -2 * Gravity"
Here I chose to apply some fancy math so I accept a more user-friendly variable to command my spring (JumpHeight). Other would have chosen to use a straight variable (JumpForce) to control the bound : easier to code, trickier to control.
Dash and Drag
I last example of movement yous can implement : a nuance. When you press the dash button your velocity will increase towards the management you are going. Like the jump you could choose a direct implementation or apply math and find a formula to make it simple to control. The maths hither are a bit more complicated and I found this to works well.
What nosotros're doing hither is scaling the forrard vector (our direction) following a dash vector. The nuance vector depends on 2 variables, the dash distance and the drag. Nosotros need to have a drag or otherwise, the histrion would never cease. the idea behind the elevate is to "simulate" the friction forces (with air, ground etc…). Elevate is an capricious value between 0 and Infinity with 0 meaning no drag at all. Hither I chose to use a Fiveector3 to stand for the drag and then I tin can specify different drag values along the axis. Then to apply the drag we just demand to add this at the end of the update part :
Character Controller Conclusion
What did we larn with this ? Well, when nosotros're using the character controller we have a lot of freedom just at the same fourth dimension we accept to code a lot of stuff ourselves even for unproblematic deportment like jumping or gravity.
The Rigidbody approach
Now that nosotros take made our controller with the graphic symbol lets meet how to make the same with a Rigidbody, and what are the differences betwixt the two approaches.
Setup
The scene setup is practically the aforementioned. The main difference is that nosotros don't have a Character Controller component fastened to the Histrion GameObject but a Capsule Collider and a Rigidbody.
On the Rigidbody, set the X and Z axis rotations to be locked. Also note that I inverse the Drag, nosotros'll see why later. The other options are default values. Nosotros can leave the Sheathing Collider to its default values.
Rigidbody Controller
This time, I won't explicate every footstep of the process because it's very similar to what nosotros've done in the Graphic symbol Controller. I'll focus on the differences betwixt the two. Here'southward the full script to give you an overview:
FixedUpdate
The first notable departure is the FixedUpdate function. This function is called by Unity earlier every "physic update". Indeed, physic updates and classic updates are not synced. To reach a disarming physic simulation, we need to calculate information technology smoothly. Unity decided to pull apart the physic update from the archetype update. This way if the frame rate is too low or too fast, it won't impact the simulation.
The idea behind the FixedUpdate function is that you lot put the physic lawmaking here. Only as you can run across, I still accept a classic Update part. Indeed, the input organization of Unity isn't synced with the FixedUpdate then nosotros have to call up the inputs in Update, stock them into a variable (here _inputs) and apply it in FixedUpdate. You could manage the inputs directly in FixedUpdate merely you would most likely have inconvenient behaviors.
Jumping & Dashing
Why didn't you lot put this into Fixed Update ? It's physic related.
Yes, but here I used these function in a discrete style : these AddForce calls are instantaneous, therefore it'south non frame dependent. AddForce is a role used to apply a forcefulness to Rigidbody. There are iv dissimilar means to use a force:
- Forcefulness : continuous and mass dependent
- Acceleration : continuous and mass independent
- Impulse : instant and mass dependent
- VelocityChange : instant and mass independent
Hither you can encounter I'm using velocityChange because I desire to have an instant reaction when jumping or dashing, and I don't care well-nigh the player'south mass.
To move the character according to the actor's inputs, we employ the MovePosition function. This function tries to motion the player to a given position while respecting the collisions rules. It besides doesn't change the velocity of the Rigidbody. This way, the role player's move are "separated" from the other physic interaction.
Y'all tin can see we don't carp ourselves with gravity or elevate. That's because the Rigidbody already does information technology for usa. You can change the drag on the Rigidbody and the gravity in the project settings.
(Exist conscientious with the drag, dissimilar the one we implemented with the Character Controller, this 1 isn't split up into different axes, so it'll touch all 3 axes at the same time!)
Main differences
Even if we want to accomplish the same goals with both techniques, they won't behave exactly the same.
Collisions
They both react with colliders but there are some slight differences. While the Rigidbody volition react very precisely and even utilize the physics material property to calculate the reaction, the Character Controller will be more than permissive : It will automatically climb slopes and steps (according to its parameters).
Extensibility
In this example nosotros didn't have a lot of features to code and the Graphic symbol Controller solution was the easiest one to do, but if we were to implement more mechanics, the Rigidbody would probably be the best way to go. It offers a lot more functions to interact with physic whereas the Character Controller doesn't, therefore we'd demand to lawmaking more than for the same feature using the Character Controller.
In Conclusion
As yous tin can meet, we can achieve the same things using both techniques only the fashion we work will modify according the choice nosotros cull.
That's why I strongly propose y'all to always take some fourth dimension to recall about earlier starting to code any player controller script!
wojtowiczthouggerve.blogspot.com
Source: https://medium.com/ironequal/unity-character-controller-vs-rigidbody-a1e243591483
0 Response to "After Setting Velocity to Zero How to Move Rigidbody Again Unity"
Post a Comment