Как сделать вид от первого лица в юнити
Перейти к содержимому

Как сделать вид от первого лица в юнити

  • автор:

Control a camera in first person

Navigate through the Scene A Scene contains the environments and menus of your game. Think of each unique Scene file as a unique level. In each Scene, you place your environments, obstacles, and decorations, essentially designing and building your game in pieces. More info
See in Glossary view while you look through a camera. In first-person, work through the lens of a camera to better frame your shots.

You can use the Cameras overlay to select and take first-person control of a GameObject The fundamental object in Unity scenes, which can represent characters, props, scenery, cameras, waypoints, and more. A GameObject’s functionality is defined by the Components attached to it. More info
See in Glossary that has a Camera or Cinemachine camera component attached to it.

While you control a camera, you can use Editor tools as you do when you use the Scene Camera. For example, select a GameObject and press the F key to frame the camera on a specific GameObject. You can also adjust the position, orientation, and scale of a GameObject while you look through a camera to change the composition of your shot.

You can adjust the overscan of cameras you directly control with the Cameras overlay. Use overscan to intentionally see more or less of the Scene in the camera’s view than what the final output of the camera produces.

The Cameras overlay supports Timeline and Animation camera path authoring and Animated cameras. Control a camera in first person to animate cameras and generate keyframes A frame that marks the start or end point of a transition in an animation. Frames in between the keyframes are called inbetweens.
See in Glossary for their GameObjects.

Codr Book

This example script allow us to control movement and rotation of camera in first person perspective. Example code is given below:

«moveSpeed» is a public variable which control movement speed of our camera and «mouseSensitivity» variable control sensitivity of mouse look.

«rotationX» and «rotationY» are private variables which are used for storing current rotation of camera.

«Start()» function will lock our cursor so player is unable to move it outside of game window.

«Update()» function will use Input.GetAxis(«Horizontal») and Input.GetAxis(«Vertical») method for getting input for movement of camera so we can move our camera left, right, forward, and backward by horizontal and vertical keys like WASD or arrow.

Input.GetAxis(«Mouse X») and Input.GetAxis(«Mouse Y») for getting input for rotation of camera.

We used «Mathf.Clamp()» function in this script for limiting rotationX between a certain range so this will prevent our camera from rotating upside down.

We used Time.deltaTime to multiply movement so this will make camera movement smooth regardless of frame rate.

first person camera controller in unity

Add this script to Main Camera in your scene for enabling simple first-person camera movement. You can tweak moveSpeed and mouseSensitivity variables as per your requirement.

Русские Блоги

3 способа установить вид от первого лица для игрока в Unity

Камера становится подобъектом капсулы, и на камеру помещается код:

Сцена плюс коллайдер

Добавьте следующий код в капсулу Player:

Это делается с помощью твердого тела

Вы можете двигаться

2. Добавьте в капсулу контроллер персонажа.

Снимите контроллер капсулы.

Просто поместите официальную документацию API напрямую, это делается с помощью символьного контроллера

3 . Сам Unity3d уже имеет вид от первого лица, нам нужно только двигать пальцами, чтобы направлять пакет.

Затем мы создаем новую папку для хранения Наша сумка

Дважды щелкните, чтобы войти в папку, затем щелкните правой кнопкой мыши в любом месте папки, чтобы открыть развертывание, а затем щелкните:

Import Package -> Charactor Controllor

(То есть импорт «Пакет управления ролями»)

Затем выскочило окно, неважно, что в нем, сначала нажмите ВСЕ (если вы не нажмете на него, unity3d может сообщить об ошибке самостоятельно), а затем нажмите «Импорт», чтобы экспортировать пакет.

Через некоторое время в папке появятся два пакета, что доказывает, что импорт прошел успешно!

Давай проигнорируем это В папке редактора перейдите в Стандартные активы-> Контроллеры персонажей-> Контроллер от первого лица (затем посмотрите следующее: «Контроллер от первого лица» — это капсула, фактически, это контроллер перспективы от первого лица)

Хорошо, давай просто поставим это Перетащите «Контроллер от первого лица» на сцену, и все готово! (Рядом с ним также находится «Контроллер от третьего лица», который представляет собой вид от третьего лица, и его также можно перетащить.)

Перспектива от первого лица и перспектива от третьего лица не могут появляться в сцене одновременно! (В противном случае он сообщит об ошибке!)

Резюме: 1, 2 метода, ролевой контроллер — управлять движением игрока, код камеры — получить вид от первого лица! Камера размещается на дочернем объекте игрока.

Третий метод не требует размещения камеры на подобъекте Player. Первые два метода должны сделать камеру подобъектом Player.

Simple first-person controls in Unity

Niklas Bergstrand

First, setup the environment and add a capsule for the player:

Add the main camera as a child on the player object and position it:

On the player object remove the capsule collider and disable the mesh renderer. Add a CharacterController to the player object:

Create a script called PlayerMovement and attach to the player object:

Open the player script and add:
-float for mouse sensitivity
-float for the movement speed of the player
-float for how high the player will jump
-float for gravity
-float to control the vertical rotation
-float for max vertical rotation angle
-three floats for player velocity
CharacterController for the CC on the player

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

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