Inventing a bicycle or implementing a friendly head rotation system for game characters

It has been a long time since any serious programming challenge. And here it is! Just started some research on bone rotation in characters’ meshes and found out that the built-in system is.. Well… Not so friendly and not so easy to use. So here’s another challenge: make a friendly, easy to use bone rotation system within LBTechnology. Of course, I’ve been doing stuff like this before, and I know ‘the shit’, but well I’ve never programmed bone rotation system ‘from scratch’. And I just didn’t know it would be that challenging. Also I’ve been aware of the trickiness of such systems from them games, which do implement such systems – i.e. famous Mass-Effect and Fallout spinning heads. But you know, you don’t know something until you try it yourself. But I’m not them Bioware nor Bethesda – I’ve got plenty of time and plenty of dope to study the problem thoroughly and no project-master whipping my ass each time I do wrong.

So, what do we basically need to implement the head-facing-target system? Well: the character having its mesh with a needed bone, the target and some code. So we’ve got the char, the target, the only thing we need – is the code, which rotates the head to face the target.

tech_task
A technical task for this problem

Well, the first and the most obvious and, perhaps, the only solution is to take the distance between the target and the head formula_v_calc, get its normal, formula_v_modulo, somehow turn it into rotation formula_rotation and set this value to the head. Looks quite easy to implement with modern game development tools.

solution
A basic solution for this problem

Ha-ha, not that easy! Far not that easy! A plenty of problems await here, of course depending on the tool you’re using.

Problem number one, coordinatie transforms. This is the first thing you’ll encounter. For example, you’ve just calculated the formula_R_value value and you’re looking at the result… And the result seems to frustrate you! Really, the bone can twist any direction except the correct! Why does it happen? Simply because you’re setting the values in world coordinates. The bone may have its own coordinate basis or it may be using it’s parent bone’s coordinates or anything else like this. So, the first thing, you should take into account is coordinate transforms from world to local for the rotating bone. My solution of this problem is to go ‘the hard way’ – this means not to use any advanced math, just transform the axis based on a pre-set rule. I called this procedure Rotation Resolving (not yet copyrighted, I hope) based on some specialized structures – Rotation Resolvers. You just point each axis, from where to get its value – i.e [Yaw-Pitch, Pitch-Roll, Roll-Yaw]. This functionality was implemented in LBSkeletalMeshControlMechanism.

Code solving problem one
...

enum RotatorAxis
{
    RotatorAxis_Yaw,
    RotatorAxis_Pitch,
    RotatorAxis_Roll,
};

struct RotatorResolver
{
    var() RotatorAxis GetYawFrom;
    var() bool bInvertYaw;
    var() RotatorAxis GetPitchFrom;
    var() bool bInvertPitch;
    var() RotatorAxis GetRollFrom;
    var() bool bInvertRoll;
};

...

function rotator ResolveRotator(rotator r, RotatorResolver resolver)
{
    local rotator res;
    
    res.Yaw=ResolveRotatorAxis(r,resolver.GetYawFrom,resolver.bInvertYaw);
    res.Pitch=ResolveRotatorAxis(r,resolver.GetPitchFrom,resolver.bInvertPitch);
    res.Roll=ResolveRotatorAxis(r,resolver.GetRollFrom,resolver.bInvertRoll);
        
    return res;
}

...

function int ResolveRotatorAxis(rotator r, RotatorAxis axis, optional bool binvert = false)
{
    if (axis==RotatorAxis_Yaw)   
    {
        if (!binvert) 
            return r.Yaw;
        else
            return -r.Yaw;
    }
    else if (axis==RotatorAxis_Pitch)
    {
        if (!binvert) 
            return r.Pitch;
        else
            return -r.Pitch;
    }
    else if (axis==RotatorAxis_Roll)
    {
        if (!binvert) 
            return r.Roll;
        else
            return -r.Roll;
    }
}

...

Problem number two, rotation restraints. This is the second thing you’ll encounter. Afer all that coordinate transform troubles you’ll finally be able to set corresponding rotation values to the rotating bone. But your character’s head would spin around its neck like it’s not attached to it. And this result will frustrate you too! Because it does look strange and funny. Well, only birds can spin their heads more than 180°, but even they’re not able to make a 360° twist (but it seems like they can, anyway I don’t care).

voa1pp
A GIF from the internet

Therefore, you’ll need to limit the available angle of rotation for each rotation axis. The most obvious solution here is to clamp your desired angle, formula_a between this axis restraints formula_a1 and formula_a2 , so you’ll get your angle like formula_clamp_2.

angle_clamps

But this solution has on big drawback – sometimes you get wrong results. For example, if your angle uses formula_deg_forma_1 format, you’ll get some trouble trying to limit the rotation from 330° to 30°. The best solution in my opinion is to use the formula_deg_forma_2 format, especially if it runs up to infinity (both infinities), otherwise you’ll get troubles with cycle transition from 180° to -180° (just like me). But my solution of this problem is to go ‘the hard way’, it’s nothing that special except the ClampRotatorAxis function, which is… Well, just lol. Anyway, I’ve implemented a function, which clamps one axis, and a function, which clamps all three rotation axes. This functionality was implemented in LBBoneRotationMechanism.

Code solving problem two
...

function int ClampRotatorAxis(int axisvalue, int min, int max)
{
    local int r,f1,f2;
    
    f1=NormalizeRotAxis(min);
    f2=NormalizeRotAxis(max);
    
    r=NormalizeRotAxis(axisvalue);
    
    if (0<=f1*unrrottodeg && f1*unrrottodeg<=180)
    {
        if (0<=f2*unrrottodeg && f2*unrrottodeg<=180)
        {
            if (0< r+(-f2))    
                    r=f1; 
                else 
                    r=f2;    
            }
        }   
    }   
    
    return r;  
}

...

function rotator ClampRotator(rotator r, optional bool bClampYaw=false, optional int Yawf1=0, optional int Yawf2=0, optional bool bClampPitch=false, optional int Pitchf1=0, optional int Pitchf2=0,
optional bool bClampRoll=false, optional int Rollf1=0, optional int Rollf2=0)
{   
    local rotator res;
    
    if (bClampYaw)
        res.Yaw=ClampRotatorAxis(r.Yaw,Yawf1,Yawf2);
        
    if (bClampPitch)
        res.Pitch=ClampRotatorAxis(r.Pitch,Pitchf1,Pitchf2); 
     
    if (bClampRoll)
        res.Roll=ClampRotatorAxis(r.Roll,Rollf1,Rollf2);  

    return res;    
}

...

Problem number three, smooth movement. This is the third thing you’ll encounter, possibly. Setting the values even if they are axis-transformed and clamped causes your character’s head to rotate as fast as it is possible. For example, if the target teleports – your char’s head will instantly (in one frame) turn there. It looks very strange, sometimes even scares the crap outta player. Sometimes this problem is not actual, but for my case it is important to solve it (just because there are some objects that can teleport). So, what is the solution? It’s quite simple: we don’t set the exact rotation on each frame, we remember this value in one of our variables (a TargetRotation variable) and increase our head’s rotation each frame until we reach this value (using some kind of interpolation if you’re a math dude). Nothing special, but there is still a lot of problems here as we deal with cyclic values – the formula_deg_forma_2 form of degree value. My solution is just as described – increasing the real rotation with certain speed until it reaches the needed value. Well, I just used the linear interpolation formula to get the value for each tick, it works fine for some reason (except that case with cycle transition from 180° to -180°), but I’ll be making a new interpolation function anyway soon. This functionality was  also implemented in LBBoneRotationMechanism.

Code solving problem three
...

function float RotateYaw(float dt)
{
    local float crot,trot,rrot;
    
    trot=NormalizeRotAxis(GetTargetRotation().Yaw);

    crot=NormalizeRotAxis(currot.Yaw);   
    
    if (bSmoothRotation)
        rrot=LinearInerpFloatValue(crot*unrrottodeg,trot*unrrottodeg,TickIndependentFloat(AngularSpeed,dt,RotationTimeScale),dt)*degtounrrot;
    else
        rrot=trot;
        
    return rrot;   
}

...

function float LinearInerpFloatValue(float current, float target, float step, float dt)
{
    local float value;
    
    if (abs(current - target) > abs(step))
    {
        if (current < target)
            value=current+abs(step); 
        else
            value=current-abs(step);   
    }
    else
    {
        if (current < target)
            value=current+abs(current - target); 
        else
            value=current-abs(current - target);      
    }
        
     return value;
}

...

And, finally, there’s the result after long time spent debugging. Well, it was rough, even for me. Also I’ve included several additional features – a hard-align (always try to look at the target) and soft-align (look at the target only when the angle is inside them restraints), a Look-At-Point and Look-At-Actor modes, which can become quite handy for mechanism interactions.

Also, there’s a video with a complete demonstration of this system:

Advertisements
Inventing a bicycle or implementing a friendly head rotation system for game characters

EVEN MORE STRANGE RUINS IN THE DESERT AND THE BLOCKTOBER

Recently I’ve been working on some updates for one of the new levels from the project «A Dream In The Fall». What happened? Well, I Just made basic geometry smoother and the whole level changed beyond recognition. Not much progress though — the sand still looks crappy and the lighting is out of order at all. But I’m on my way to fix it!

Actually it’s not true, because I seem to be one of that dudes, who do things and only then think (best case scenario), so everything resulted in a complete rework of everything from scratch including element locations, paths, triggers and other important stuff. And yes, I’m still not satisfied with the result! Well, I’m doing such updates with almost every asset, and this iterative refienment proceess seems to stop at never. What is the problem here? Just only total time spent? Well, while I’ve been working in this industry, I’ve seen some dudes being planning, projecting, constructing in the paper each damn level before making it in the editor. It took hours, days, months and the result was still a piece of guano (wild animals’ shit). Also there are some examples from big guys in modern industry making #blocktober flashmob, demonstraiting their pedantic approach to level design. Oh, come on, that just thier work for bread ‘n’ butter. What I do — is a total random-driven process! Once I’ve worked with random level generators, you know what — I’m one of them random generators.

Just made several assets (stone slabs or whatever), took them each in the hand and started dropping them in this hot low-polygonal sand. And, of course, the most important hemorrhoids here is collision models on these meshes. Well, I’ve managed to solve it — just puth everything in blocking volumes, lol. Well, that’s all about this short story of making shit even shittier, but removing some shit from this shit on each iteration.

EVEN MORE STRANGE RUINS IN THE DESERT AND THE BLOCKTOBER

Improved interaction mechanics

Earlier I’ve managed to make a fair action system and an inventory-based interaction mechanics, so currently developed interaction is a physical proximity-based interaction, as postulated earlier: a touch or a hit between objects (characters<->objects). So, basically, the player can touch anything in the level, but not everything in the level is able to react — the interaction is only performed in a mutual manner. At least, I’ve made such a conclusion. The concept is the following: there are some interactions, which are performed by the player’s character, the character can perform an interaction on an arbitrary object, influencing its state. The idea is quite simple: an actor makes the other actor’s mechanism to perform handling of a certain event, each event is described and handled in the event handling mechanism. The active counterpart of the interaction couple is LBSimpleInteractionMechanism (LBBasicInteractionMechanism), while the passive counterpart is LBEventHandleMechanism, however I’ve made some loopholes for the interaction mechanism to be able to handle events by the React() function. The following four procedures do form the interaction mechanism’s core, so when an additional functionality is needed, they are modified or overridden.

function Interact()
{ }
function React()
{ }
function bool CanInteract()
{ }
function bool CanReact()
{ }

But typically there’s no need to modify any code at all, so all needed data is set in the editor. To describe a new interaction, the designer should set its name and some values, which are used by this interaction.

char_interact_params_3

Thus, the passive counterpart-actor’s mechanism, the LBEventHandleMechanism, performs the real event handling (what a surprise!). It is interacted by sending this mechanism SetParamInt() with param name ‘RaiseEvent‘ and a param value, containing this event’s id. After activation of a certain event, its params are set. For example, we can enable or disable movement, set movement speed of the current actor or do many other interesting things by this params.

object_interact_params_1

For more convenience, interaction mechanism in a player’s character is wrapped in a character controller mechanism, which also wraps the inventory mechanism and many others. So, the player first activates a certain action, for example, a touch action of the player’s character. Also it’s quite a convenient way to perform some checks, but in the code, of course.

char_interact_params_1

Now, all together. I’ve made a draft touch animation and a corresponding touch action, which is performed by our character. Well, the character doesn’t seem to have any hands, so it has to touch everything with its face, lol, so the current animation looks quite strange. Finally, we’re able to perform the touch action by pressing a key on a keyboard, as described earlier, so the pipeline can proceed. Next, this action plays a touch animation, which triggers the anim notify, which send the interaction mechanism a message via Interact(), and then, the interaction mechanism perform a coresponding interaction. It should be noted, that the action cannot be pefrormed (the animation won’t play), if we receive a negative answer from an interaction mechanism via CanInteract(). This is the fair way, I suppose, when you don’t touch things, that are not ment to be touched.

So, in this example, when animation time reaches a certain position in the touch animation, the animation notify is sent to the character’s interaction mechanism, which handles all the stuff by the HandleAnimNotify(). In this example, the actioncode is set to 401 and notifytype is set to ActionNotifyTypes_ActionPerform. Next, the check is performed, and, if this check is passed, the interaction is performed — the PerformInteraction() is called, which also says the interaction mechanism to perform a certain interaction immediately.

function HandleAnimNotify(int actioncode, int actiondata, 
ActionNotifyTypes notifytype)
{
 ...
 if (actioncode == 401)
 {
  if (CheckInteract(TouchInteractionID))
  {
   PerformInteraction(TouchInteractionID); 
  } 
 }
 ...
}

When the cube (okay, the golem) is touched and all above stuff is performed, the event handling mechanism sets several values, which turn on movement, rotation and other logics. Also, I’ve made a camera effect, so when the golem is touched, the view toggles to a cinematic camera via the following kismet sequence.

Kismet_nodes_3

Well, that’s the core of the interaction system, the concept looks quite acceptable, however it may contain some hidden problems, like simultaneous interaction with multiple objects. But for now, that’s how the interaction system is organized. Now we can see the in-game interaction example, where the object is being activated by character’s touch.

It seems to be one of the most complex parts of the game logic, but very perspective at the same time. Also I’m looking forward to making use of it in some even more complex cases. But for now, just a simple case: the player’s character activates some cubes. The video below shows, how it looks all together.

 

Improved interaction mechanics

Improved action mechanics

So, I’ve made some improvements in the action-interaction system. It has been a long-needed update. In different games player is able to perform different actions, not only just run, jump and shoot. Well, honestly, a major part the gameplay nowadays is built around actions and interactions, so inadequate and ineffective solutions are unacceptable. This leads us to a completely new domain of problems: we need a separate mechanism for performing character’s actions. The concept is simple: there are some actions, each can be performed by the character. An action has certain properties, like it’s relationship with animation — an action may or may not have an animation, and it’s relationship with character state and other actions — an action may or may not have effects on the game pawn (except the animations effect). Thus, we come to a fairly easy solution — the LBBasicCharacaterController, which is capable of performing actions, which means the ability to play animations and change pawn’s states (virtually, of course). Basically, we’ll be working only with current character’s logic, leaving all underlying activity to the basic character controller. So, we’re interested in only in these methods:

function HandleActionStart(int startedaction)
{ }
function HandleActionStop(int stoppedaction)
{ }
function HandleAnimNotify(int actioncode, int actiondata, 
ActionNotifyTypes notifytype)
{ }

Which do handle action start, action end and animation notifies, which may or may not trigger during the action animation. If we don’t need any character-specific logic or we just want a Garry’s Mod-styled animation player, we can just use the editor. For the designer it’s really simple — all what’s required is to fill out the Character Action List in the editor, which contains all the necessary data.

char_interact_params_1_1.PNG

For example, here I’ve made four basic actions: touch, pick up, put down, carry, three last interactions I’ve been describing earlier, the touch action and the appropriate interaction I’ll describe later. Also I’ve made some auxiliary actions, which really don’t have any effect in the game, except they do play animation. All options of this actions are shown below, for example, them options of the touch action mean that this action is controlled by the certain animation: the action starts with the animation and ends with this animation, also it may have activation restrictions and switch links. What is activation restriction? It’s simple — the action cannot be performed from any actions (state-actions), except these. And the switch link is a type of  a bridge between the actions — upon its finish, the action can be automatically switched to another one. Well, I’ve made some comments (been trying my best) in sources on GitHub.

char_interact_params_1_2

Next thing, what is required — the proper animation, set up and linked to the LBBlendByAction animnode, which blends all animations. There’s also a default node, which is used to blend out, when the default action is active.

animtree_nodes_1_1.PNG

Thus, all, what’s required now is to call a needed action by the SetParamInt() function with param name ‘BeginAction‘ and param value containing the action code. Also, this can be performed from any sub-system, but I’ve chosen Kismet and its keyboard events.

kismet_nodes_4

Well, let’s test this functionality. I’ve made some random (though interdependent) animation sequences (though craggy) for the character, then plugged them into the new action system. There’s a state-action, which defines character’s state — the ‘Sit_Tie_Idle‘ action. There are also two gateway-actions — the ‘Sit_Tie_In‘ as an entrance into this state and the ‘Sit_Tie_Out‘ as an exit. And there are two actions, performed exclusively from the ‘Sit_Tie_Idle‘ state — the ‘Sit_Tie_Gym_1‘ and the ‘Sit_Tie_Gym_2‘.

Now we can make our character do different things. For example, we can watch our strange character doing its strange exercises (some kind of gym, maybe?). However, everything happens in the right order, for example, it can’t just start walking or jumping from a stretched pose, it has to stand up first.

Improved action mechanics

Movement mechanics

Almost the first time doing serious bipedal movement mechanics and animation. Let’s make a first step into the complex character animation (or not). Anyway, here’s the workflow. Honestly, once I’ve been involved in such an affair… And things did not go very well, but that was then. Anyways, now is the first real attempt to create an acceptable bipedal character movement animation and mechanics. First, I’ve made a complete redesign of an old version of movement mechanic, which was a special pawn and was very hard to use. Well, now it looks shiny and new, now this code goes to a new separate mechanism — LBCharacterWalkMovementMechanism, which is now based on LBCharacterMovementMechanism (empty at the moment, lol) and conains all the code, needed for performing pawn movement and blending the animation. It also has all parameters, which are used to regulate pawn’s speed and acceleration.

walk_movement_mechanism

It has the forward speed parameter and a forward speed coefficient to handle forward speed, same to the sidestep (strafe?) speed. Also it has accel rate, which is used to speed the pawn up, when it wants to run. Another important thing here is the angular speed, which is represented by angular speed parameter and an angular speed coefficient, which are used to handle pawn’s rotation. Also it has move direction, which is used to point the desired movement direction. It’s worth noting, that pawn rotation is quite an interesting task itself (later on this). Second, I’ve made several frames of animation for the character, the walker (xw_char). It wasn’t easy, because someone’s left in it’s feet only one bone. Maybe it was even me. Anyways, there are two fairly appropriate animations sequences:

Simple walk animation:

xenowalker_walk_gifxenowalker_walk_gif_side

Simple run animation:

xenowalker_run_gifxenowalker_run_gif_side

Other intermediate and supportive animations are quite crappy to be shown here. It should be noted that I used the walk and run cycle tutorials by Richard Williams as a reference (found all over the internet) for my walk and run animations. As a result, we’ve got the following animtree:

Where BlendByAngSpeed node does blending between middle, left and right turn sequences and BlendByFwdSpeed node does blending between walk and run sequences. Also, while blending between walk and run is quite a simple task, but blending between rotations seems to be more complex. Using unique animation sequences turned out be the best way to solve this problem, others, like using direct bone rotations may cause weired effects in my animtree during blending between states, for example. Finally, we’ve got the result, let’s see how does it look all together:

Walk and run animations in game:

Turn and turn in place animations in game:

However, complex tests reveal some flaws, like minor body jerking and leg rattling, also there’s still no jump and sidestep implementation. And ofcourse, the camera is terrible, but controlling with joystick (gamepad) partially solves the problem. Nevertheless, in general it looks not too bad.

Movement mechanics

«The Cave» level, step three

The third step of level design. Some interactable objects were added to the level. They are: inventory objects (items which can be picked up), movers, carriers and immovable interactable objects.

Many of these objects don’t have meshes at this time (placeholders are used), but for some of them I’ve developed 3D models.

Placed in the level they look quite satisfactorily (from a far distance of course).

Later I’ll be compiling the scene once again, because of totally crappy lighting and unwanted gloss. And yes, I found a way to make some parts of the scene brighter or darker.

«The Cave» level, step three

«The Cave» level, step two

The second step of designing the level. At first, some smaller rocks were added. They don’t look nice in themselves:

But a propper texture, a nice illumination and a suitable environment made them look pretty good, at least for now. Then, some foliage was added to the level. They are some ivy branches, which I’ve made recently:

This foliage doesn’t look good too, especially the leaves, but I think it’s okay for now. Finally, these simple things made the level look live. But water is still no good – I think I’ll just use one of my old shaders to keep the haemorhoid away. On the next step, gameplay elements are going to be added.

How it looks all together:

And the perspective:

«The Cave» level, step two