Moving in Unity

Source: Internet
Author: User

Turn from: http://angryant.com/2014/03/07/Moving-in-Unity/, describes in detail several ways in which objects move in unity, and gives code descriptions that are helpful for deepening unity understanding, thanks to Angryant. I use my humble English proficiency in a simple translation, hope understanding.

Introduction

Moving something around on the screens in Unity are really not this hard. The point of this post was therefore not to introduce do you are accomplished, but rather to point out where do you ' re Doing it wrong?.

Generally Unity moves objects using one of three systems:

      • Direct transform manipulation.
      • Physics.
      • Navigation.

In the end, movement are measured on transform updates. I make the distinction from the point of view of where you provide the input. Technically you could argue that animation should is up there as well, but I choose to lump this in with transform Manipul ation, since disabling the application of movement by the animation system have no other side effects.

As a side-note, since 4.3 it is possible to partially or completely disable have the animation system update the TRANSFO RM hierarchy.

Moving objects in unity is not a very difficult thing to do, this article is not about the specifics of the move, but primarily to support errors that may occur during use.

In general, Unity moves objects in several ways:

      • Direct use of Transform
      • Physical
      • Navigation

Moving is usually judged by updating the transform, which is mainly distinguished by the different inputs. Technically, you might argue that you need to add "animations", and I choose to summarize the animation and move operations, after all, moving out of the animation system has no effect on the mobile system. Note that, starting with the Unity4.3 version, unity may be slowly removing the animation's effect on the moving update.

Transform

So long as the goal are simply to move a object and nothing else, modifying the values of the transform component, or usin G its various useful methods to does so, are all you need.

This includes directly animating the transform via the animation windows or by enabling animation root motion.

However chances is, your situation is more complex than this and your would do well to read on.

If you are simply moving an object, you can do it by directly modifying the transform component values or other methods, including using animations directly through the animation window or enabling actions.

Physics

When your object on any-needs to affect and/or is affected by the physics simulation, you need-make some extra cons Iderations. Simply slapping on a collider and calling it a day would ruin your next.

To properly participate as a dynamic part of the physics simulation, an object needs to has a rigidbody component attache D somewhere in its transform hierarchy.

The physics system considers separate transform hierarchies as separate objects, so one (and only one) Rigidbody component Would mark the rest of its hierarchy as dynamic.

Multiple rigidbodies in the same hierarchy leads to undetermined behaviour (read:weirdnessness), Haven only exception bein G If those rigidbodies is connected by a joint–thus making their behaviour again well defined.

When your object needs to be physically affected or affected by other objects, you need to think extra. In order to implement the dynamic part of the physical system, you need to add the Rigiboy component to the object layer, and the physical system will move the layer group as a separate object, so as long as an object is added with a rigid body component, the remainder of the object hierarchy will be marked as dynamic. The fact is that rigidoby, even as a sub-object, also receives physical effects, which can affect both the parent class and the subclass. Multiple rigibody in an object hierarchy can have bizarre effects, unless different rigid bodies are grouped together by connection, such as different parts of a person's body.

Kinematic

"But I don ' t need gravity or forces or any of the other nonsense!" –be cool, that's what the "kinematic" switch was for. This basically tells the physics simulation, which your object is dynamic, but you'll take care of all its movement.

Kinematic rigidbodies is not being affected by forces or collisions, but would collide with Non-kinematic Rigidbodies, Sendi NG collision events and pushing them out of the (assuming there is colliders present somewhere in the transform Hiera Rchy of the object).

"Why do add the Rigidbody in the first place?" Things work just fine without! "–if are Unity Pro, I would direct your attention at the profiler as you move about– If not, take my word for it, it's not a joyous sight.

Any object (unique transform-hierarchy) with no rigidbody present are treated by the physics simulation as static. For optimal performance, all static colliders is baked into a static collision geometry, securing optimal performance whe n Doing collision checks.

However every time one static collider (note that this have nothing to does with the static flags on the gameobject–just th E presence of absence of a rigidbody on the object in question) are moved, the whole static collision geometry is marked di Rty and regenerated.

This isn't a terribly costly operation, so moving pieces of level geometry from one position to another from time to time is fine. However moving a character of one or more static colliders around every frame would cost you.

Note that while moving by directly modifying the transform of a kinematic rigidbody are just fine, you'll get better resu LTS for rapid movement by using the moveposition and moverotation rigidbody functions.

The former would effectively "teleport" the physical object–fine for short distances and minor rotations Longer moves. Moverotation and-position effectively "drags" the object from A to B.

If there is no need for gravity or force, you can switch through the kinematic. Kinematic Rigidbody is not affected by force and collision, but it can still produce collision events and launch collisions with Non-kinematic Rigidbody, and can be transformed by Tranform.

"Why should we consider Rigibody first?" "And even without it things work just as well---then you'd better look at the performance of the move in the Unity Profiler.

Collisions without rigibody are treated as static in the physical system, and all static collisions are baked into static collision geometry to ensure optimal collision detection from the optimization system.

When moving a static collider, all the static collisions in the system are regenerated, so moving a large number of static collisions will be a very costly task.

If there is a need for this, you can use kinematic rigidbody to move through transform, or use the Moverotation, Moveposition method of the Rigidbody class. The kinematic Rigidbody method is suitable for short-range movement or small rotational efficiency, slightly worse at long distances, and moverotation and-position is highly efficient at "dragging" objects from A to B.

Kine-not-so-matic

"OK, so maybe it would pretty useful if my character could walk to walls, get pushed by others and that sort of thing ..." No problem. Disable the kinematic flag and start moving via the Rigidbody component. If you wanted proper forces and all that, I ' m sure you ' re already all over the Addforce function and all that.

However if you still want strict control–just with a touch of presence–you should look at directly setting the Velocit Y property of the Rigidbody.

Given sideways and forward movement input, forming a velocity vector is easy. By setting the velocity of the rigidbody you add that information to the physics simulation as well as tell it to update t He position of the object smoothly.

That includes pushes from the other rigidbodies or pushbacks from static geometry. However directly setting the velocity would override any directional, and so momentum would remain unchanged.

Therefore consider factoring in some acceleration when building your target velocity vector–for a more natural look afte R your character is pushed or makes a abrupt change of direction.

You can use force for control, but for precise control, you can consider setting the Velocity property directly (do not set every step in physics, but can be used in the case of an emergency change of state). By setting velocity, it is equivalent to telling the physical system to gently update the object's position. But this approach would overturn all directions and the kinetic energy would remain the same, and the appropriate application would be a fast-changing situation, such as a car's acceleration.

Navigation

Parallel to the physics simulation you find the Navigation runtime. Similarly to how the rendered world model was defined by static and dynamic geometry and the physics World model is defined by static colliders and rigidbodies, the navigation world model was defined by interconnected navigation mesh and dynamic Obstacles.

While the static physics geometry defines areas of no access, navigation mesh defines areas is which. This information was used for finding a valid path from point A to B, but more importantly it's used to constrain characte RS and inform them of their surroundings.

The physics simulation can be used for this as well and traditionally is. However the data covered by the physics system are vastly more complex and their ability to define traversable space is a SID E effect of its ability to define non-traversable space.

This is where your end up spending-too much time blocking off sections of scenery and later testing that there was Inde Ed no holes in that. Navmeshes on the other hand define a surface on which characters of a given height and with a given radius can move.

Just as the model in the rendering can be divided into static and dynamic, the model in the physical system can be divided into static collision body and rigid body, and the model in the navigation world may be divided into the connection body and the dynamic block. Navigation in unity can be performed in parallel with physical simulations, static object geometry defines the impassable area, and the navigation grid defines the areas that can be used in the pathfinding, but more importantly the limitations of the roles themselves and the information around them. Navmeshes, on the other hand, defines a surface on which a character can walk with height and radius set. (The middle translator does not understand)

Navmeshagent

Similarly to the Rigidbody component, the Navmeshagent component wires a object to the navigation runtime. In stead of the "kinematic" switch, however, the navmeshagent has separate updateposition and Updaterotation toggles.

To get things going, you can either set a path by one of the many accessors for that or directly set the velocity. Assuming that the navmeshagent was configured to update the position, this would start smoothly moving the object like with The rigidbody–only this time constrained by the navigation meshes rather than collision geometry.

In addition to pathfinding and staying on the navigation mesh, the navigation runtime would also attempt to the Variou s navmeshagents avoid one-another by adjusting velocity based on the position and velocity of nearby dynamic obstacles and Navmeshagents.

Avoidance can completely tweaked though–so that one navmeshagent can ignore it completely or itself be ignored or Wei GH different navmeshagents differently.

Similar to the Rigidbody component, the Navmeshagent component navigates at run time, Navmeshagent has separated updateposition from updaterotation.

To make the object walk, you can set the path or set the speed vector directly. If Navmeshagent is allowed to update the position, the object will move smoothly, at this time the object is constrained by the navigation meshes, not the collision geometry; In addition to finding the way and staying on the navigation grid, in the course of navigation, The agent will try to have different navmeshagent at different speeds, depending on the distance and speed between the different dynamic objects and the navmeshagent, thus avoiding the other. Evasive behavior is really found, for example, in parallel auto-running in multi-road racing, you will find that faster speed vehicles, if there are slower cars, they will automatically turn, without impact.

Direct Control

"Pathfinding?" I just need to move this character around based on input. " Sure, Fine–that is where you just go Set the velocity of the navmeshagent rather than trying to set a path or Destinatio N for it.

Like with the Rigidbody, this starts moving the navmeshagent smoothly and tells the runtime on its current velocity–g Iving other agents a chance to avoid. Note that even if you don't let the navmeshagent directly control the position of your character, you should still feed t He velocity back to it–in order to keep the avoidance runtime up to date.

If you are moving a role around the input, you can set the speed of the navmeshagent instead of re-setting the new path or the new path. After you reset the speed, the navmeshagent will slowly move past and tell the runtime the current location (for other agents to dodge). Even if you don't let navmeshagent directly control the position of the object, you should also reset the speed back, in order to keep the run-time evasion behavior.

Added: A few days ago, in the long track transformation when found that if the speed will fall down, so the solution is to re-find the road after the speed variable reset.

Animation

"Wat! You do not count this as one of the three ways of moving stuff! "–nop, quite right. However root motion is awesome, so let's briefly touch on how we tie the and the other systems for much greatness.

While most of the animation system does are not a too much concern for your movement logic, one very useful feature I S. By analysing animations on import, the surface movement relevant for those animations are calculated and later blended a s the animations is blended.

By default the animation system would, with root motion enabled, move a animated object around by directly updating the TR Ansform position based on the root motion of the currently playing animation blend. Animation nicely synchronised with the world movement.

I ' ll root my own motion, thank you

However while that looks mighty cool, it really isn ' t very considerate of your carefully crafted physics simulation or you R neatly marked navigation runtime. Luckily it does give an on by allowing you to override the actual application of the root motion.

This was accomplished by, on the same game object as your animator component, attaching a script implementing the method on Animatormove. Once that method is defined, the animation system would no longer directly apply root motion and in stead call this Impleme Ntation post-evaluation.

In the implementation of the Onanimatormove callback, you could then update a target velocity vectors by simply dividing an Imator.deltaposition by Time.deltatime and similarly rotation. And once we have desired movement in the form of a velocity vector, plenty of the earlier described scenarios become Relev Ant.

Most interactive niceness

"Great, I ll take one of each!" Sure, no problem. Well ... It's not exactly straight forward, but it's indeed possible to combine all of the these things to get something that's respo Nsive, embedded in your simulations and looks great.

The chain of data goes a little something like this:

    • Player controlled characters:
      1. Feed input to the animator, resulting in nicely blended animation s and Root motion.
      2. Generate a target velocity in onanimatormove.
      3. Set Velocity of navmeshagent (configured to not update position or rotation).
      4. Set Velocity and rotation of non-kinematic rigidbody (properly constrained on rotation so it doesn ' t tip over).
      5. Map transform position to navigation mesh via navmesh.sampleposition.
    • Non-player characters or indirectly controlled player characters:
      1. Set destination or Pat H of Navmeshagent.
      2. Feed desiredvelocity of Navmeshagent to animator.
      3. Repeat As for player controlled characters from 2.

What this setup does isn't give you are responsiveness to being bumped into. However velocity-wise this isn't something your movement implementation should handle directly unless you are OK with Bre Aking that nice root motion setup you just established.

In stead I would recommend using queries on the surrounding physics and navigation environment to inform the animation STA Te machine of special conditions like "player wants to go full speed, but there ' s a wall both units from here" and handle s Lowing down, stopping and similar in there where the result would look good.

One simple trick are to does a navigation raycast along the forward vector of the moving transform for some amount of look-ah EAD distance and if a navigation mesh edge is hits and does a physics raycast further forward from a point slightly elevated From that edge hits point.

With this setup can very simply gather information about where the character are headed–if into a steep wall or Perha PS to a ledge or obstacle which could be leapt.

Unity Hacks

Since apparently I lumped just about everything to that project, unsurprisingly the Unity Hacks project have some work on This is the form of wired up movement. Particularly the Mover component attempts to create a System-agnostic movement interface as well as some simple movement o N Networked setups not covered here.

While not complete or on any of the answer, I hope that with the information provided here, it turns out useful for Y Mul

    • Mover.cs

Drizzle mark: unity,movetion

Moving in Unity

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.