Velocity unity что это
Перейти к содержимому

Velocity unity что это

Rigidbody.velocity

Thank you for helping us improve the quality of Unity Documentation. Although we cannot accept all submissions, we do read each suggested change from our users and will make updates where applicable.

Submission failed

For some reason your suggested change could not be submitted. Please <a>try again</a> in a few minutes. And thank you for taking the time to help us improve the quality of Unity Documentation.

Description

The velocity vector of the rigidbody.

In most cases you should not modify the velocity directly, as this can result in unrealistic behaviour. Don’t set the velocity of an object every physics step, this will lead to unrealistic physics simulation. A typical example where you would change the velocity is when jumping in a first person shooter, because you want an immediate change in velocity.

When should I use velocity versus addForce when dealing with player objects?

I’m confused about these two methods in the Unity framework. Both make the player object move, stop, change direction, etc. When should one be used over the other and when is one appropriate?

5 Answers 5

You’d use velocity to move the object at a constant rate (for example a bullet) and AddForce() to add movement (for example a spaceship thruster). Also note there are two «types» of movement; force and impulse. For a spaceship thruster you’d use impulse.

Although there’s already an accepted answer, I think there are some additional details worth covering.

Using Velocity

When you set velocity, you’re overriding absolutely everything else that might affect that object’s movement. In some situations this is desirable, such as setting the initial velocity of a bullet once at the moment it’s fired, as in trojanfoe’s example. Just be wary, because when used in the wrong situations it can cause issues:

If multiple sources/scripts try to modify the same Rigidbody’s velocity by setting it directly (ie. body.velocity = foo ), then whichever one runs last wins, and the others have zero effect. This can lead to order of update bugs, in particular causing entities to hover or fall slowly (because downward acceleration due to gravity gets overridden before it can accumulate)

If you’re setting velocity every frame, collisions with other objects can be a bit weird. It’s as though your object is being propelled by an engine with infinite torque — no matter how much velocity it loses on an impact, it’s back up to top speed on the very next physics step, and its velocity isn’t deflected away from the impact. This can lead to launching objects you collide with, or small objects being able to push huge ones much more easily than it seems like they should, or objects sliding slowly along static barriers instead of deflecting away/along them.

Both of these effects can be desired sometimes. For example, when I’m making Kinect games and I want the player’s virtual avatar’s limbs to be able to interact with the physics scene, I usually move those bodies using direct velocity setting. Because the player’s actual hand is in a known place and didn’t slow down from collision with that virtual object, their virtual hand needs to do the same to stay in alignment, so in this case we actually want to override all other physics effects to get it there.

AddForce and Friends

AddForce and similar helper functions, by contrast, are made to cooperate with everything else going on in the physics world. If multiple sources/scripts AddForce to a Rigidbody, all of those effects get added together to create a net change in the object’s movement (which, depending on how it’s calculated, may also be order-independent). This helps avoid one script completely stomping some other physics effect.

AddForce comes in four flavours by specifying the optional ForceMode parameter, which are useful for different things:

If you’re trying to model a continuous push over time (eg. something you’re applying every FixedUpdate), like a car driving or a rocket burning or a gravity well pulling, you want Force or Acceleration. (Depending on whether you want heavy objects to accelerate slower)

If you’re modelling a sudden, sharp change in motion, like firing a bullet, recoiling from an explosion, or bouncing off a barrier, then you more likely want Impulse or VelocityChange.

Using AddForce helps you achieve more physical realism, but it can also require that you spend more time thinking through the physics of your behaviour. For instance, if you want your body to have a finite acceleration up to a target speed, so that it reacts more realistically to collisions than setting the velocity every frame, you’ll probably want a calculation similar to this helper function:

The reason I call all of these «helper functions» is that technically you could achieve all the same ends with:

(I think. It’s possible Unity’s PhysX/Box2D-based physics solvers buffer changes through AddForce separately, but I haven’t seen obvious consequences of this)

Unity Character Motor

Когда-то давно, еще во времена Unity 3, мне стало интересно как работает физика персонажа. И я заглянул в класс CharacterMotor. Класс был написан на JavaScript, был огромный, страшный и непонятный. Я решил переписать его на C#, попутно отрефакторив. Недавно я вспомнил про свой старый CharacterMotor, решил еще немного подправить его и поделиться им. Тем более, тема физики персонажа не очень популярная (я вообще не видел никакой информации), хотя довольно интересная.

1. Введение

Я взял за основу CharacterMotor из Unity 3. В Unity 4 CharacterMotor не менялся, а вот в Unity 5, это абсолютно новый класс. Новый CharacterMotor, значительно уменьшился в коде, и видимо, и в функционале. Я не особо разбирался в нем и почти не использовал его, но заметил, что скольжение с крутого склона теперь не работает, и вообще качество кода мне не понравилось. Видимо писался он на скорую руку. Также Unity 5 перешел на новый PhysX 3, но в CharacterController я никаких изменений не заметил. Так что, думаю, мой CharacterMotor не устарел.

Character Motor | Unity Character Motor

2. CharacterController

Обычно персонаж не является обычным физическим объектом и работает по своим законам физики. В Unity для персонажа используется CharacterController. Это комбинация коллайдера в форме капсулы и метода Move. Метод Move двигает персонажа в указанную позицию, обрабатывая при этом коллизию. Обработка коллизии тут тоже не обычная, например, коллизия обрабатывается так, чтобы персонаж мог свободно подниматься на небольшие склоны, но не мог на большие, или auto stepping — фича, которая позволяет персонажу подниматься на маленькие препятствия. CharacterController не совместим с RigidBody, это значит, что он не может взаимодействовать с другими физическими объектами. Это создает некоторые проблемы: персонаж не может двигать другой физический объект, а другой объект не может сдвинуть персонажа. Кинематические объекты вообще свободно проходят сквозь персонажа, что делает проблематичным создание лифтов и движущихся платформ.

3. CharacterMotor

Вместо RigidBody мы должны использовать свой класс, в Unity это CharacterMotor. Хотя, CharacterMotor — это намного больше, чем RigidBody. CharacterMotor отвечает за любые движения нашего персонажа, например: ходьба, бег, скольжение, падение, прыжки, движение на платформе, на лифте, подъем по вертикальной лестнице, плавание. Все это реализуется, фактически, с помощью различных ухищрений, а не законов физики. Ведь персонажи обычно ведут себя не по законам, например: персонаж может немного управляться во время прыжка или падения, или просто резко останавливаться или менять направление движения. В Painkiller Дэниел мог ускоряться, просто прыгая без разбега. Конечно это все не сильно нарушает законов игровой физики, и можно было бы попытаться сделать максимально все физически корректно, но ведь проще просто ограничить скорость падения, чем вычислять сопротивление воздуха.

Я разделил мой CharacterMotor на 3 partial класса: CharacterMotor, CharacterMotor_Movement и CharacterMotor_Jumping. В оригинальном классе был еще класс отвечающий за движение на платформе, но я убрал его.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *