User Tools

Site Tools


en:guides:beginners:input_controls

Part 10 - Input Controls

Now to add some keyboard control so that our hero is able to jump and run around.

First we'll need to define some keys. You'll notice that one key (quit) is already defined in the [Input] section, which is used as the default input set.

Let's add a few more:

[Input]
KEY_ESCAPE   = Quit
KEY_LEFT     = GoLeft
KEY_RIGHT    = GoRight
KEY_LCTRL    = Shoot
KEY_LSHIFT   = Jump

This assigns labels to keys. These labels can be accessed in the code.

You can add code the Update() function to detect these keys. The Update() function is tied to the Orx core clock so the keys can be checked on every frame:

if (orxInput_IsActive("GoLeft"))
{
}
 
if (orxInput_IsActive("GoRight"))
{
}

In order to affect the hero object, it will need to be assigned to a variable so that it can be worked with. Change the HeroObject creation line in Init() to be:

hero = orxObject_CreateFromConfig("HeroObject");

And declare the variable at the top under the include orx.h line:

orxOBJECT *hero;

Now it is possible to affect the object in code. We'll add a vector direction as a speed to the object based on the key pressed:

orxVECTOR leftSpeed = { -20, 0, 0 };
orxVECTOR rightSpeed = { 20, 0, 0 };
 
if (orxInput_IsActive("GoLeft"))
{
    orxObject_ApplyImpulse(hero, &leftSpeed, orxNULL);
}
 
if (orxInput_IsActive("GoRight"))
{
    orxObject_ApplyImpulse(hero, &rightSpeed, orxNULL);
}

Compile and run. Our hero will run left and right with the cursor keys. Sweet! Except he runs off really quick and doesn't stop.

He needs some damping on his body to slow him down when a speed is not being applied:

[HeroBody]
Dynamic           = true
PartList          = HeroBodyPart
LinearDamping     = 5

Run that and our hero will decelerate to a quick stop when no key is pressed.

Next, we can add a jump:

orxVECTOR jumpSpeed = { 0, -600, 0 };
 
if (orxInput_HasBeenActivated("Jump"))
{
    orxObject_ApplyImpulse(hero, &jumpSpeed, orxNULL);
}

This code is like the previous key input code but this one only applies impulse just the once when the key is pressed - not if it's held down.

Compile and run. Your hero can now jump around:

Cool he can jump around using the shift key. But our hero turns over when he hits a platform edge. We can fix that by fixing his rotation:

[HeroBody]
Dynamic           = true
PartList          = HeroBodyPart
LinearDamping     = 5
FixedRotation     = true

Run it again. Much better!


Next: Part 11 – Running and Standing.

en/guides/beginners/input_controls.txt · Last modified: 2021/07/14 22:57 (3 years ago) by iarwain