- UEngine.Ru
- Как работает World Direction?
- UEngine.Ru
- Сразу 2 проблемы на тему поворотов.
- Setting Up Character Movement
- In this How-To guide, you will create a playable character that exhibits different forms of Character Movement.
- Creating a New Project
- Creating the Player Character
- Creating Input Key Mappings and Input Movement Events
- Work-In-Progress Blueprint
- Work-In-Progress Code
- Creating Input Key Mappings and Input Action Events
- Completed Blueprint
- Finished Code
- Setting up the Game Mode
- Creating the Locomotion Blend Space
- Creating the Crouch Locomotion Blend Space
UEngine.Ru
Русскоязычное сообщество Unreal Engine 4
Как работает World Direction?
В блюпринте, при использовании команды Add Movement Input, для перемещения аватара, есть векторная переменная World Direction, предназначенная для передачи направления перемещения. Она представляет из себя три значения: X, Y, Z.
Т.к. мне было необходим дискретный поворот на прямые углы, я вводил значение этой переменной сам. И выяснил что, при Y и Z равных 0, а X = 2 я получаю направление вверх по экрану, а при X = 1 вниз по экрану, камера прицеплена независимо и не вращается. Более того каждое четное значение X поворачивает вверх, а нечетное вниз. Я этого и добивался, но:
Суть вопроса: Я не понимаю как это работает. Это же вектор, увеличение значения X, должно увеличивать длину вектора по координате X, почему четность/нечетность значения X меняет угол поворота на 180 градусов?
Вообще World Direction работает от -1 до 1 по всем осям. По сути, это вектор направления объекта. В отличии от поворота, тут идет направленность в определенную сторону по вектору.
На примере понятнее:
Скажем у нас есть WD на вектор x:1 y:0.5 Соответственно, объект будет направлен в эту точку, в соответствии с плоскостью. Если судить по рисунку, то будет примерно градусов 20-30. Если взять точку x:-0.5 и y:-0.5, то угол будет 45 градусов внизу слева, ровно как и -1 -1.
Вот почему четность влияет на угол, не понятно. Тут нужно смотреть, как работает твой код.
_________________
Просьба, не писать вопросы по движку в ЛС. Я не единственный, кто знает UE4, и поэтому пишите на форум или в группу.
Источник
UEngine.Ru
Русскоязычное сообщество Unreal Engine 4
Сразу 2 проблемы на тему поворотов.
Всем доброго времени суток. Есть такая картина:
И сразу 2 проблемы с ней
Первая весьма распространенная и даже уже как-то раз справлялся с ней, но чего-то запнулся
Пытаюсь вращать «объект» мышкой вот таким вот способом
и все бы ничего, но проблема -180-180 никуда не делась.
На «границе» игрок вместо того чтобы немного повернуться совершает поворот на 360 градусов.
Помню что тут надо прилепить хитрое условие, но какое.
Проблема 2:
При попытке придать игроку движение вперед через Add Movement Input с вращением вообще начинает происходить что-то невменяемое
Двигаю так:
А по поводу первой проблемы, то логику вообще тут всю нужно переписывать, она глупая, да и не работает.. Нужно устанавливать поворот, а не добавлять его.. Подумайте о разнице.
И да.. Вот к чему приводят уроки «Как сделать. «. Вы это делаете, а как заставить работать это под себя, не знаете..
_________________
Просьба, не писать вопросы по движку в ЛС. Я не единственный, кто знает UE4, и поэтому пишите на форум или в группу.
Верно, но вы же хотите поворачивать объект в сторону курсора. То есть устанавливать его ориентацию так, что бы он смотрел на курсор..
Вам нужно Set Actor Location. А что бы получить поворот от точки до точки (например от персонажа до курсора), можно воспользоваться Find Look At Rotation.
_________________
Просьба, не писать вопросы по движку в ЛС. Я не единственный, кто знает UE4, и поэтому пишите на форум или в группу.
Верно, но вы же хотите поворачивать объект в сторону курсора. То есть устанавливать его ориентацию так, что бы он смотрел на курсор..
Вам нужно Set Actor Location. А что бы получить поворот от точки до точки (например от персонажа до курсора), можно воспользоваться Find Look At Rotation.
Я и так это делаю, Если глянете на блупринт.
Дело в том что Set Actor Location работает мгновенно и именно устанавливает вращение. Мне же надо чтобы объект поворачивался за курсором, но делал это не мгновенно.
Основная разница:
Если мой курсор был справа а оказался слева то в случае с Set actor location объект просто начнет смотреть в сторону курсора.
Таким же способом он плавно повернется в ту сторону.
Плюс если же что-то помешает этому развороту (стенка / другой объект), то в первом случае это будет проигнорировано, а во втором он «упрется»
На данный момент моя проблема выглядит так:
Есть рабочее вращение которое работает так как нужно:
https://www.dropbox.com/s/stt408u8e9ciw . .webm?dl=0
Если же я попытаюсь добавить движение вперед — поворот накрывается
https://www.dropbox.com/s/y6ajfsbotzc8q . .webm?dl=0
Та самая галка (которая Orient to move или как-то так) у меня стоит само собой false
Rotation, а не Location. Моя ошибка..
Во вторых, есть блок интерполяции ротатора, и там как раз есть возможность установить короткий путь до цели (то есть от 179 до -179 будет поворачиваться через 180, а не через 0). Но его нужно использовать как раз Set Actor Rotation. Более того, я бы плавно изменял вектор направления, а не поворот. Тогда проблем не будет вообще с этим. Вот так:
Но у вас допущена ещё одна очень важная ошибка. Но она из-за простого незнания.
Convert Mouse Location To World Space функция выдает не координаты того, куда указывает курсор, а координаты самого курсора. То есть координаты на мировом пространстве вашего изображения. Грубо говоря, координаты курсора рядом с камерой. То есть сейчас у вас поворот, по сути, должен происходить вверх, а не вокруг объекта (но из-за использования только Yaw этого не происходит). Вам же нужно выводить координаты того, куда указывает курсор, а для этого делать линейную проверку под курсором через LineTrace.
_________________
Просьба, не писать вопросы по движку в ЛС. Я не единственный, кто знает UE4, и поэтому пишите на форум или в группу.
Источник
Setting Up Character Movement
In this How-To guide, you will create a playable character that exhibits different forms of Character Movement.
Character Movement provides a locomotion system for humanoid characters to traverse through your world. The Character Movement Component is an Actor Component that provides modes of movement for Character classes, including walking, falling, swimming, and flying. Additionally, the Character Movement Component features robust network gameplay integration and provides a framework to help developers create custom networked movement.
For additional documentation on Network Replication in Unreal, see Networking and Actor Replication
In this How-To Gameplay Guide, you will create a Character class, script it’s movement logic, Input, and create an Animation Blueprint which will help determine which state your Character is in, and then play the corresponding animation.
Choose your implementation method:
Creating a New Project
Begin by signing into the Epic Games Launcher and creating a New > Games > Blank > Project named CharacterMovement.
To animate your Character, you will require the Animation Starter Pack which is available to download for free from the Epic Games Marketplace . Click the Free button to download and add the Animation Starter Pack to your Epic Games Library.
From your Library, search for your Animation Starter Pack and click Add to Project, then from the Select the Project to Add the Asset to menu, search for and select your CharacterMovement project file, then click Add to Project.
Upon adding the Animation Starter Pack to your project, you will notice its presence in the Content Browser.
Begin by creating a New > Games > Blank > C++ project named CharacterMovement.
To animate your Character, You will require an Animation Starter Pack which is available to download for free from the Epic Games Marketplace . Click the Free button to download and add the Animation Starter Pack to your Epic Games Library.
From your Library, search for your Animation Starter Pack and click Add to Project, then from the Select the Project to Add the Asset to menu, search for and select your CharacterMovement project file, then click Add to Project.
Upon adding the animation starter pack to your project, you will notice its presence in the Content Browser.
Creating the Player Character
A Character class is required for your Player to control. A character is a pawn that comes with a Character Movement Component to provide a locomotion system for humanoid characters to traverse through your world. Follow the steps below to set up your character.
Click the Add/Import button to create a new Blueprint Character class named BP_PlayerCharacter.
Double-click your BP_PlayerCharacter to open its class defaults, then in the components tab select the Mesh(CharacterMesh0) Skeletal Mesh Component, and navigate to the Details panel.
Click image to expand.
In the Mesh category, select the drop down arrow adjacent to the Skeletal Mesh variable, and from the drop down menu select SK_Mannequin.
In the Details panel, navigate to the Transform category, and set the Mesh’s Location and Rotation to (0,0,-90).
Your Character’s Skeletal Mesh will now be oriented in the direction of the forward facing Arrow Component as shown in the image below.
Navigate to the Components tab to select your Mesh component, then click Add Component and in the drop down menu search for and select SpringArm, then name your Spring Arm Component «SpringArmComp«.
Navigate to the Details panel, and in the Camera Settings category enable the Use Pawn Control Rotation.
Enabling use Pawn Control rotation will rotate the camera relative to the spring arm.
In the Camera category, set the socket offset to (0,0,30) then navigate to the Transform category and set the SpringArmComp’s Location to (0,0,50).
With your SpringArmComp selected, click the Add Component button, then in the drop down menu search for and select Camera to add a Camera Component named CameraComp.
In the Components tab, select the Character Movement Component, then navigate to the Details panel, and in the Character Movement (Rotation Settings) category, enable Use Controller Desired Rotation and Orient Rotation To Movement.
In the Character Movement:Walking category enable the Ignore Base Rotation variable.
Setting Ignore base rotation to true will tell the character to maintain its current world rotation, and ignore any changes in rotation of the base it’s standing on.
In the Character Movement Nav Movement category, navigate to the Movement Capabilities and select the drop down arrow to reveal additional variable settings, navigate to the Can Crouch Boolean and click to enable it.
Compile and Save.
A Character class is required for your Player to control. A character is a pawn that comes with a Character Movement Component to provide a locomotion system for humanoid characters to traverse through your world. Follow the steps below to set up your character.
In the C++ Class Wizard, create a new Character class named PlayerCharacter, then navigate to the PlayerCharacter.h file and declare the following class definitions:
Navigate to the PlayerCharactor.cpp file and add the following class libraries:
In the APlayerCharactor::APlayerCharacter constructor method declare the following
Compile your code.
In the Editor, navigate to your C++ Classes folder, then right click on your PlayerCharacter class and in the C++ Class Actions drop down menu select Create Blueprint class based on PlayerCharacter. Name your Blueprint Bp_PlayerCharacter.
Click image to expand.
Double-click your BP_PlayerCharacter to open it’s class defaults, then in the Components tab select the Mesh(CharacterMesh0) Skeletal Mesh Component, and navigate to the Details panel.
Click image to expand.
In the Mesh category, select the drop down arrow adjacent to the Skeletal Mesh variable, and from the drop down menu select SK_Mannequin.
Your Character’s Skeletal Mesh will appear oriented in the direction of the forward facing Arrow Component as shown in the image below.
Compile and Save.
Creating Input Key Mappings and Input Movement Events
You will need to set up some custom logic that will move your character when an Input key; such as W,A,S, or D is pressed.
Navigate to Edit > Project Settings > Input, then in the Bindings Category click the + sign next to Action Mappings to add the following:
In the Bindings Category click the + sign next to Axis Mappings to add the following Axis Mappings.
In the Content Browser, double click your BP_PlayerCharacter to open it’s class defaults, then right click on the Event Graph and in the drop down menu search for and select MoveForward.
Click image to expand.
Drag off from the execution pin of your InputAxis MoveForward node and in the drop down menu search for and select for the Add Movement Input node, then connect the Axis Value pin of the InputAxis MoveForward node to the Scale Value pin of the Add Movement Input node.
Click image to expand.
Right click on the Event Graph and in the context menu search for and select Get Control Rotation, then drag off the Rotator return value pin, and in the drop down menu search for and select Break Rotator.
Click image to expand.
Drag off from the Break Rotator node’s Z(Yaw) pin, and in the drop down menu search for and select Make Rotator, then drag off from the Make Rotator node’s Rotator Return value pin and in the drop down menu search for and select Get Forward Vector.
Click image to expand.
Drag off from the Get Forward Vector node’s Vector Return Value pin and plug it into the Add Movement Input node’s World Direction pin.
Click image to expand.
Right-click on the graph again, and search for and select Move Right for your Input Axis Event.
Click image to expand.
Drag off the execution pin of your InputAxis MoveRight node and in the drop down menu search for and select for the Add Movement Input node, then connect the Axis Value pin of the InputAxis MoveRight node to the Scale Value pin of the Add Movement Input node.
Click image to expand.
Drag off from the Make Rotator node’s Rotator Return Value pin and in the drop down menu search for and select the Get Right Vector node, then drag off from the Vector Return Value pin and plug it into the Add Movement Input node’s World Direction pin.
Click image to expand.
Your completed Movement Input Events Blueprint graph will look as it does below.
Click image to expand.
Right-click on the Event Graph, then search for and select for the InputAxis LookUp event node, then right-click, search for and select for the Add Controller Pitch Input node.
Click image to expand.
Drag off from the Axis Value pin of the Input Axis LookUp node and connect to the Val pin of the Add Controller Pitch Input node. Drag off from the execution output pin of the InputAxis LookUp node and connect to the execution input pin of the Add Controller Pitch Input node.
Click image to expand.
Right-click on the Event Graph, then search for and select for the Input Axis Turn event node, then right-click, search for, and select the Add Controller Yaw Input node.
Click image to expand.
Drag off from the Axis Value pin of the Input Axis Turn node and connect to the Val pin of the Add Controller Yaw Input node. Drag off from the execution output pin of the Input Axis Turn node and connect to the execution input pin of the Add Controller Yaw Input node.
Click image to expand.
Click Compile and Save.
Work-In-Progress Blueprint
At this point in the process, your Blueprint graph should resemble the image shown below.
Click image to expand.
You will need to set up some custom logic that will move your character when an Input key such as W,A,S, or D is pressed.
Navigate to Edit > Project Settings > Input, then from the Bindings Category click the + sign next to Action Mappings to add the following Action mappings.
In the Bindings Category click the + sign next to Axis Mappings to add the following Axis Mappings.
In your PlayerCharacter.h, declare the following class methods
In your PlayerCharacter.Cpp, implement the following logic for your APlayerCharacter::MoveForward, and APlayerCharacter::MoveRight class methods.
Next, navigate to the APlayerCharacter::SetupPlayerInputComponent method, and implement the following code.
Compile your code
Work-In-Progress Code
PlayerCharacter.h
PlayerCharacter.Cpp
Creating Input Key Mappings and Input Action Events
Now that you have completed the Blueprint scripting logic for your Move Forward, Move Right, Look Up, and Turn input events, you will need to finish implementing your Action Mappings for your Jump, Crouch, and Sprint input events.
Right click on the Event Graph, then in the All Actions for this Blueprint drop down menu, search for and select your Jump Action Event.
Click image to expand.
Drag off from your InputAction Jump node’s Pressed execution pin, then in the drop down menu, search for and select the Character function Jump.
Connect the execution pin of your InputAction Jump node to the execution pin of your Jump node.
Click image to expand.
Drag off from the InputAction Jump node’s Released execution pin, and in the drop down menu, search for and select the Character function Stop Jumping.
Click image to expand.
Right click on the Event Graph and in the drop down menu, search for and select the Input Action Sprint.
Navigate to the Components tab, then click and drag your Character Movement Component on to the Event Graph.
Click image to expand.
Drag off the Character Movement pin and from the drop down menu, search for and select Set Max Walk Speed. Set the Max Walk Speed float value to 1000, then connect the Pressed Execution pin of the InputAction Sprint node to the Input Execution pin of the Set Max Walk Speed.
Click image to expand.
Drag off from the Character Movement pin, then search for and select for another set Max Walk Speed node. Set the Max Walk Speed float value to 600, and then connect the Released execution pin of the InputAction Sprint node to the Set Max Walk Speed execution input pin.
Click image to expand.
Right-click on the Event Graph, and in the drop down menu search for and select your Input Action Crouch.
Drag off from the InputAction Crouch node’s Pressed execution pin, then in the drop down menu, search for and select the Character class function Crouch.
Click image to expand.
Drag off from the InputAction Crouch node’s Released execution pin, then in the drop down action menu search for and select the Character class function Un Crouch.
Click image to expand.
Compile and Save your Blueprint.
Completed Blueprint
Your completed Blueprint should resemble the image shown below.
Click image to expand.
Now that you have completed the Code scripting logic for your Move Forward, Move Right, Look Up, and Turn input events, you will need to finish implementing your Action Mappings for your Jump, Crouch, and Sprint input events.
Navigate to your PlayerCharacter.h file and declare the following class methods
In your PlayerCharacter.cpp file, implement the following logic for your APlayerCharacter::BeginSprint and APlayerCharacter::EndSprint class methods.
Implement the following logic for your APlayerCharacter::BeginCrouch and APlayerCharacter::EndCrouch methods.
Navigate to your APlayerCharacter:: ::SetupPlayerInputComponent method and declare the following code:
Compile your code.
Finished Code
PlayerCharacter.h
PlayerCharacter.cpp
Setting up the Game Mode
The GameMode defines the game’s set of rules. These rules include what default pawn the player will spawn as when the game is launched. You will need to set up these rules in order to spawn the Player Character that you have created.
In the Content Browser, click the Add/Import button and create a new Blueprint class, when the Pick a Parent Class menu appears, select Game Mode Base and name your new Gamemode class Bp_GameMode.
Click image to expand.
Double click Bp_GameMode to open it’s class defaults, then navigate to the Details panel Classes category, and for the Default Pawn Class select Bp_PlayerCharacter.
Compile and Save your Blueprint.
Navigate to Edit > Project Settings > Maps & Modes, and in the Default Modes category, select Bp_GameMode.
Click image to expand.
The Game Mode defines the game’s set of rules. These rules include what default pawn the player will spawn as when the game is launched. You will need to set up these rules in order to spawn the Player Character that you have created.
In the Editor navigate to your C++ classes folder. Right click your CharacterMovementGameModeBase and from the C++ Class Actions menu, select Create Blueprint class based on your CharacterMovementGameModeBase, then name your new Gamemode class Bp_GameMode.
Click image to expand.
Double click Bp_GameMode to open it’s class defaults, then navigate to the Details panel Classes category, and for the Default Pawn Class select Bp_PlayerCharacter.
Compile and Save your Blueprint.
Navigate to Edit > Project Settings > Maps & Modes, and in the Default Modes category, select Bp_GameMode.
Click image to expand.
Creating the Locomotion Blend Space
Now that you have a character that possesses the input functionality to move in your level, you will need to create Blend Spaces for your movement states (sprinting, jogging, and crouch walking).
Blend Spaces are special assets that allow for blending of animations based on the values of two inputs. You will create your own blend spaces that move between forward and backward and left and right movements based on the character’s movement speed or direction.
In the Content Browser, click Add/Import > Animation > BlendSpace, when prompted to pick a skeleton, choose the UE4_Mannequin_Skeleton, then name your Blend Space Locomotion_BS.
Double click to open the Locomotion_BS Blend Space. In the Asset Details tab, navigate to the Axis Settings category, then select the arrows adjacent to the Horizontal Axis and the Vertical Axis to see more variable details.
In the Horizontal Axis settings, change the Name variable to Direction, then set the Minimum Axis Value to -180, and the Maximum Axis Value to 180.
In the Vertical Axis Settings, change the Name variable to Speed, then set the Maximum Axis Value to 1000.
Compile and Save.
Navigate to the Asset Browser, then within the filters search bar type Idle_Rifle_Hip, then drag and drop the Idle_Rifle_Hip asset into the Blend Space at Direction 0.0, and Speed 0.0.
Click image to expand.
Repeat the previous step, inserting the Idle_Rifle_Hip asset into:
Direction 180, Speed 0.
Direction 90, Speed 0.
Direction -90, Speed 0.
Direction -180, Speed 0.
Click image to expand.
In the Asset Browser tab Filters search bar type Walk_Fwd_Rifle_Ironsights, then drag and drop the Walk_Fwd_Rifle_Ironsights asset into the Blend Space at Direction 0.0, and Speed 250.
Click image to expand.
Next, in the Asset Browser tab Filters search bar type Walk_Lt_Rifle_Ironsights, then drag and drop the Walk_Lt_Rifle_Ironsights asset into the Blend Space at Direction -90 and Speed 250.
Click image to expand.
In the Asset Browser tab Filters search bar type Walk_Rt_Rifle_Ironsights, then drag and drop the Walk_Rt_Rifle_Ironsights asset into the Blend Space at Direction 90 and Speed 250.
Click image to expand.
In the Asset Browser tab Filters search bar type Walk_Bwd_Rifle_Ironsights, then drag and drop the**Walk_Bwd_Rifle_Ironsights asset into the Blend Space at Direction 180 and Speed 250, then drag and drop it again at Direction -180 and Speed 250**.
Click image to expand.
In the Asset Browser tab Filters search bar type Jog_Fwd_Rifle, then drag and drop the Jog_Fwd_Rifle asset into the Blend Space at Direction 0.0, and Speed 500.
Click image to expand.
Navigate to the Asset Browser, then within the filters search bar type Jog_Lt_Rifle, then drag and drop the Jog_Lt_Rifle asset into the Blend Space at Direction -90, and Speed 500.
Click image to expand.
Navigate to the Asset Browser, then within the filters search bar type Jog_Rt_Rifle, then drag and drop the Jog_Rt_Rifle asset into the Blend Space at Direction 90, and Speed 500.
Click image to expand.
From the asset browser search bar filter type Jog_Bwd_Rifle_Ironsights, then drag and drop an Jog_Bwd_Rifle_Ironsights asset into the Blend Space at Direction 180 and Speed 500, then drag an additional Jog_Bwd_Rifle_Ironsights at Direction -180 and Speed 500.
Click image to expand.
Complete your Blend Space by navigating to the asset browser, search for and select Sprint_Fwd_Rifle_Ironsights, then drag and drop an Sprint_Fwd_Rifle_Ironsights asset into the Blend Space at Direction 0 and Speed 1000,
Click image to expand.
Compile and Save.
Your completed Locomotion_BS will look as shown in the image below!
Creating the Crouch Locomotion Blend Space
With your Locomotion Blend Space complete, you will now need to create your Crouch Locomotion Blend Space.
In the Content Browser, click Add/Import > Animation > BlendSpace, when prompted to pick a skeleton, choose the UE4_Mannequin_Skeleton, then name your Blend Space LocomotionCrouch_BS.
Double click to open the Locomotion_BS Blend Space. In the Asset Details tab, navigate to the Axis Settings category, then select the arrows adjacent to the Horizontal Axis and the Vertical Axis to see more variable details.
In the Horizontal Axis settings, change the Name variable to Direction, then set the Minimum Axis Value to -180, and the Maximum Axis Value to 180.
In the Vertical Axis Settings, change the Name variable to Speed, then set the Maximum Axis Value to 300.
Repeat the previous steps from the Creating The Locomotion Blend Space section, and place your assets into the Blend Space at the values below.
Источник