How to make a character jump in Unity
Jump is one of the most used features in games. So, if you are learning game development you need to know how to make your player jump. There are two major ways to make an object jump. The first one is to use physics and the second method is to use animation. It totally depends on your game type whether you should use physics or animation to jump.
The general rule is, if your character movements in the game do not satisfy physics law then you should use animation to make the character jump. In this tutorial, we will walk you through the steps to implement jump in Unity.

Unity simple Jump script
Avoiding Mid Air jump with Ground check in Unity
The above script works flawlessly but the character can jump even in midair. If you don’t want your character to jump in midair you need to check if the character is standing on the ground. You can use collision detection also but continuous collision monitoring will affect the performance of your game. You can check the offset for difference in heigh like in the video above but it will work only for plane grounds.
The image below shows the other scenarios that you can use

So, the best way to check if the object is on ground is using the box cast with a layer mask.

To Check if character is on the ground
This trick will work in case of a Plain ground with no ups and down.
- Create a new layer for the ground. We will use using it for the box cast.
- Add the script below and set the size of box, max distance and layerMask.
If you want to learn how to create this script then check out this video

Recommended Asset
You can get this Physics based character controller from the Unity Asset store if you don’t want to code. It contains all the required features that you need in a 3D character controller. The player can easily interact with the physical environment, move and push objects, slide on surfaces, climb, wall jump and so on.
Implement jump with Animation
Implementing jump with animation is recommended for non-physics games. But there are a few drawbacks of this method.
- You cannot change the height of jump during the game.
- Jump looks unnatural.
This doesn’t mean there are only disadvantages. You can control the speed of animation which in turn controls the time required for the jump. This control is not available with physics.
Animating character to simulate jump
- Open the animation window by going to window>Animation>Animation.
- Select your character in the hierarchy window and click create new animation on the Animation window.
- Save the animation as Player_jump.
- This will create an Animation clip and add an Animator to the character.
- Click the record button on the Animation window. Don’t change anything on the Animation window without selecting the record button. If you do then the changes will not be saved.
- Set the player to ground position for the first and the last keyframes.
- Select the middle keyframe and set the character position for the highest position jump point.
- Click on the Curves tab on the bottom of the Animation window.
- Use the Animation curve to make the jump animation look natural.
- Click on the Animation name and select create new.
- Create another empty animation clip called Rest. This will be our default state.
Adding Animator to the character
While creating Animation, Unity would have added the Animator component to the Player. This step is only required if your player does not have an Animator component.
- Select the character in the Hierarchy window.
- Select the animation in the project window and uncheck loop time.
- Find the Animator component of your player and add it to the component of the player.
- Open the Animator window by going to WIndow>Animation>Animator.
- You should see the animation clips inside the Animator. If not, add the animation clip Player_jump and Rest to animator.
- Add the script below to play the animation when space bar is pressed.
Animator window setting
- Set rest clip as the default state by right clicking on the Animation state.
- Make a transition from Player_jump to rest. Check “has exit time”.
Script to implement jump with animation
You can control the animation speed by selecting the Animation state and setting the speed parameter. If you are using character controller then check out our tutorial on implementing jump with Character controller in Unity.
If you have any other questions on player jump, leave them in the comments below.
Основы создания 2D персонажа в Unity 3D 4.3. Часть 3: прыжки (и падения)
Всем привет. Продолжаем серию уроков по созданию 2D персонажа. В предыдущих двух частях мы сделали персонажа, который может находиться в двух состояниях: покой и бег вправо-влево. Возможно, для очень простой игры этого будет достаточно. Но мы не будем останавливаться на достигнутом и сегодня научим нашего персонажа прыгать.
Наша цель звучит просто, но в ее реализации будут некоторые тонкости. Во-первых, нам надо как-то определить, что персонаж находится в состоянии прыжка. Это будет немного сложнее, чем определение состояния бега. Во-вторых, нужно прикрутить соответствующую анимацию. Здесь мы могли бы поступить аналогично анимациям покоя и бега — циклично воспроизводить соответствующие кадры анимации, пока персонаж находится в состоянии прыжка. Но мы реализуем более гибкий вариант. Состояние прыжка на самом деле состоит из двух состояний: взлет и свободное падение. Кроме того, бывают частные случаи — только взлет и только падение. Если мы прикрутим одну общую анимацию для этих двух состояний (например, поджатые ноги и развевающийся на ветру плащ) — это может выглядеть нормально, но не совсем реалистично. В реальности, когда человек прыгает, положение его тела, рук, ног отличается при взлете и при падении. Мы создадим такую анимацию, которая будет учитывать скорость взлета/падения и в зависимости от нее переключать соответствующий кадр анимации.
Загрузим наш проект и сцену. В папке Assets — Sprites у нас остался последний неиспользованный спрайт Jump. Проделаем с ним уже знакомую операцию по нарезке спрайта на коллекцию изображений. Затем в окне Hierarchy выберем Character и перейдем в окно Animation. Для прыжка нам понадобиться несколько файлов анимаций, а точнее — семь. Это равно числу кадров в спрайте Jump. Давайте создадим эти анимации, называя их Jump1, Jump2 и т.д.

Теперь добавим в каждую анимацию по одному изображению из спрайта Jump, по порядку: спрайт Jump_0 в анимацию Jump1, спрайт Jump_1 в анимацию Jump2…

В окне Animator (не Animation!) у нас автоматически создались элементы для новых анимаций, но они нам теперь не понадобятся. Выделим их и удалим клавишей Delete (анимации также удалятся из соответствующего списка в окне Animation, но чуть позже мы их вернем). Создадим в Animator‘е два новых параметра: Ground с типом Bool и vSpeed с типом Float. Первый будет обозначать, находится ли персонаж на земле или в прыжке, а второй будет хранить текущее значение скорости персонажа по оси Y, то есть скорость взлета/падения. В зависимости от нее мы будем применять соответствующую анимацию из наших семи анимаций прыжка.

Теперь кликнем правой кнопкой по любому свободному месту в окне Animator и выберем Create State — From New Blend Tree. В окне Inspector переименуем созданный элемент как Jump.

Создадим два перехода между анимациями: Any State -> Jump и Jump -> Idle. То есть, из любого состояния мы можем перейти в состояние прыжка, а из состояния прыжка перейти в состояние покоя. Напоминаю, как делаются переходы: клик правой кнопкой по первой анимации, Make Transition, клик левой кнопкой по второй анимации. Для первого перехода зададим условие Ground — false, для второго Ground — true.

Теперь кликнем дважды по Jump. Откроется элемент Blend Tree. В него мы добавим наши семь анимаций прыжка, а переключение между ними будут происходить в зависимости от значения параметра vSpeed. По умолчанию в Blend Tree сейчас установлен параметр Speed — поменяем его на vSpeed в окне Inspector.

В этом же окне нажмем на плюсик и выберем Add Motion Field. Это нужно проделать семь раз. Создадутся семь полей для наших семи анимаций. Снимем флаг Automate Thresholds, чтобы можно было вручную устанавливать значения параметра vSpeed, при достижении которых будет производиться смена анимации в Blend Tree. Перетащим в каждое поле по анимации и зададим значения vSpeed. Вот что должно получиться (кстати, после этих действий удаленные из списка в окне Animation анимации Jump1—Jump6 вновь появятся):

С анимацией пока закончим. Теперь нам надо научится определять, когда персонаж находится на земле, а когда — в воздухе, то есть в прыжке. Перейдем в окно Scene. Создадим пустой игровой объект, назовем его GroundCheck. Выделяем его в окне Hierarchy и перетаскиваем мышью на Character (все в том же окне Hierarchy!). Теперь объект GroundCheck будет дочерним по отношению к Character и будет перемещаться вместе с ним, а объект Character приобретет соответствующую стрелку, скрывающую дочерние объекты. Кликнем по стрелке и вновь выберем объект GroundCheck. Назначим ему иконку, чтобы видеть объект на сцене. На скриншоте я указал, как это сделать:

В окне Scene переместим GroundCheck в ноги персонажа. Тем самым, мы сделали объект, который будет использован для определения нахождения персонажа на земле.

Теперь нам надо определить, а что же является землей? Очевидно, это наша платформа, но игра об этом пока не знает. Кстати, давайте создадим копию платформы для тестирования прыжка (лучшим способ будет создание префаба на основе платформы, но сейчас давайте просто выделим Platform и нажмем Ctrl+D). Разместим вторую платформу правее и выше первой.

Выделим любую из платформ и обратим внимание на верхнюю часть окна Inspector. Там есть поле Layer со значение Default. Оно обозначает принадлежность объекта к тому или иному слою. Кликнем на Default, выберем Add Layer, зададим в поле User Layer 8 имя Ground. Снова выделим платформу, и вместо слоя Default установим слой Ground. Для второй платформы тоже установим слой Ground.

Таким образом мы определили, что наши платформы будут землей. Объект GroundCheck будет проверяться на предмет пересечения с объектами слоя Ground, т.е. с нашими платформами. Если будет обнаружено пересечение — персонаж находится на земле. Делаться это будет в скрипте CharacterControlleScript, созданном в предыдущей части. Давайте откроем его на редактирование.
В начало скрипта добавим новые переменные в добавок к уже существующим:
А в начало метода FixedUpdate следующие строки:
Теперь добавим в скрипт метод Update, в котором будем обрабатывать нажатие клавиши прыжка. Мы будем делать это в методе Update для большей точности управления — этот метод вызывается каждый фрейм игры, в отличии от FixedUpdate, который вызывается через одинаковое определенное время и обычно, при хорошем FPS, вызовы происходят реже вызовов Update.
Итого, полностью скрипт будет выглядеть так:
Сохраняем скрипт, возвращаемся в Unity. В Hierarchy выделяем Character. Перетаскиваем объект GroundCheck в поле Ground Check скрипта CharacterControllerScript, а в поле What Is Ground устанавливаем Ground.

Итак, в нашем скрипте, в методе FixedUpdate проверяется пересечение объекта GroundCheck с объектами, принадлежащими слою Ground. Это достигается при помощи метода Physics2D.OverlapCircle. В аргументах этого метода также задан радиус определения пересечения. Затем, в переменную аниматора Ground устанавливается результат определения нахождения на земле, а в переменную vSpeed — текущая скорость персонажа по оси Y. В зависимости от этой скорости применяется та или иная анимация прыжка из семи анимаций в Blend Tree. Сам прыжок задается в методе Update при нажатии на пробел, путем придания вертикальной силы компоненту Rigidbody2D.
Прежде чем запускать игру давайте немного изменим значение гравитации, а то скорость прыжков получится медленной, как на Луне. Заходим в меню Edit — Project Settings — Physics 2D. В окне Inspector устанавливаем значение Gravity Y = -30. Запускаем игру! Если все сделано правильно, увидим примерно следующее:
Капитан Коготь умеет бегать и прыгать. При прыжке, в зависимости от состояния (взлет/падение) и от скорости применяется соответствующая анимация. На видео хорошо заметно, что при прыжке в окне Animator происходят переключения между анимациями в элементе Blend Tree. При этом, если персонаж просто падает с платформы (т.е. в прыжке нету фазы взлета, пробел не нажимался) — работают только те анимации, для переключения которых заданы отрицательные значения скорости, что делает поведение персонажа более реалистичным. Конечно, для лучшего эффекта необходимо больше анимаций и более тонкая настройка значений скорости.
Что ж, на этом все. Основа для 2D персонажа создана. Какие к ней прикрутить дополнительные возможности — зависит уже от конкретной игры. Спасибо за внимание!
Как сделать прыжок в unity 3d
![]()
Всё ещё ищете ответ? Посмотрите другие вопросы с метками c# unity3d разработка-игр или задайте свой вопрос.
Site design / logo © 2022 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2022.6.10.42345
How to make a character jump in Unity
Jump is one of the most used features in games. So, if you are learning game development you need to know how to make your player jump. There are two major ways to make an object jump. The first one is to use physics and the second method is to use animation. It totally depends on your game type whether you should use physics or animation to jump.
If your character movements in the game do not satisfy physics law then you should use animation to make the character jump. In this tutorial, we will walk you through the steps to implement jump in Unity.
Jump in Unity using physics
Simple jump with Space bar
- Create a new script called Character_jump using create>new C# script in the project window.
- Copy and paste the code below to the script.
- Attach Rigidbody component to your character.
- Attach the script to your character.
- Set your jump parameters in the inspector window.
- You character is ready to jump
Unity Jump script
Avoiding Mid Air jump
The above script works flawlessly but the character can jump even in midair. If you don’t want your character to jump in midair you need to check if the character is standing on the ground. You can use collision detection also but continuous collision monitoring will affect the performance of your game.
Check if character is on the ground
- Save the initial offset between character and ground.
- Check If the distance between character and ground is greater than the offset.
- If yes then execute the jump script.
Example script
Implementing jump with physics in Unity 2D
The above script can be used for 2D jump with little alterations. Do the following changes in script.
- Change Rigidbody to Rigidbody2D.
- Change Vector3 to Vector2.
- Here is the final script.
Jump script for Unity 2D
Controlling fall in Jump physics
We can control the jump height by changing the jump force. But the speed at which the object will fall down depends on the mass and gravity. Changing gravity will affect other objects in the game. So, you can increase or decrease the mass of the gameobject to control the speed of fall. You also need to change the jump force to achieve the same jump height as earlier if you change the mass.

Implement jump with Animation
Implementing jump with animation is recommended for non-physics games. But there are a few drawbacks of this method.
- You cannot change the height of jump during the game.
- Jump looks unnatural.
This does’t mean there are only disadvantages. You can control the speed of animation which in turn controls the time required for the jump. This control is not available with physics.
Animating character to simulate jump
- Open the animation window by clicking window>animation.
- Select your character in the hierarchy window and click create new animation on the animation window.
- Save the animation as Player_jump
- Click the record button on the animator window.
- Set the ground position of the first and the last frame.
- Select the middle frame and set the character position for the highest position jump point.
- Use the animator curve to make the jump animation look natural.
- Create another empty animation clip called rest. This will be our default state.
Adding animator to the character
- Select the character in the Hierarchy window.
- Select the animation in the project window and uncheck loop time.
- Click add component in the inspector window and add animator.
- Add the animation clip Player_jump to animator.
- Add the script below to play the animation when space bar is pressed.
Animator window setting
- Set rest clip as the default state.
- Make a transistion from Player_jump to rest. Check “has exit time”.
Script to implement jump with animation
You can control the animation speed to control the motion of the player.
If you have any other questions on player jump, leave them in the comments below.
3D Character Animations in Unity
This article will show how to set up a 3D character model in Unity with animations for idle, running, and jumping; if you don’t have a rigged version of your character, that is not a problem. You can see how to use Mixamo for Unity to rig your character in my previous article.
For movement, this character uses the simple Character Controller movement set up in a previous article.
Setting Up the Animator
The first thing you need to do is create an Animator Controller if we don’t already have one and assign it to the Animator component on the model. Then you can drag your animations for the character into the Animator window for the Controller.
Now, if you enter Play Mode, the animation set to the Default State will play.
Switch to Running
Next, create a Float Parameter for Speed that will control the change from Idle and Run. Then make a Transition from Idle to Run and add the Condition if Speed is greater than 0. After that, make another Transition from Run back to Idle with the Condition if Speed is less than 0.1. To make an instant transition disable Has Exit Time on each.
If you do not want the animation to change the position of the root bone, make sure to disable Apply Root Motion. Typically you don’t want it to be enabled.
To access the Speed Parameter and change the animations, you need a reference to the Animator in the Player script. Then grab the component in Start.
The horizontal input is what will determine in the run, or idle animation plays. The GetAxisRaw is not smoothed over time, so it will give you an instant animation change when used. Then you set the Float Parameter Speed to the absolute value of the horizontal input, so -1 returns as 1.
The Player now runs when there is horizontal input, but it doesn’t flip directions based on which way you move.
Flip the Player
To control the flipping of the Player, you will need to add a bool.
To flip the Player, you will change the y-axis rotation between 0 and 180 degrees. It will be 0 and not reversed when moving right (positive horizontal) and at 180 and flipped when moving left (negative horizontal).
The Player will now flip to the direction of movement.
Jumping
For controlling when the jump animation plays, you can use either a Trigger or a Bool Parameter. Using a Bool allows you to stop the animation at any point in case the Player touches the ground before the animation finishes. With a Trigger, the animation would continue until finished before switching. For the Transition back to Idle or Run, you can add another Condition for Speed to determine if it goes straight to Idle or Run animation.
So the script doesn’t set the Jump Parameter every frame; you need to add a bool to know if the Player is jumping.
If the Player is on the ground and jumping, you set the jumping bool to false and tell the Animator to switch out of the jump animation by setting the Bool Jump to false. Then when the Player presses the Space key, you change jumping to true and tell the Animator to start the jump animation by setting the Bool Jump to true.