User Tools

Site Tools


en:guides:beginners:input_controls

This is an old revision of the document!


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 [MainInput] section which is used by the [Input] section.

Let's add a few more:

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

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

You can add code the run() function to detect these keys. The run() 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 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_IsActive("Jump") && orxInput_HasNewStatus("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:

Run it again. Much better!

Next up, Running or Standing.

en/guides/beginners/input_controls.1445597969.txt.gz · Last modified: 2017/05/30 00:50 (7 years ago) (external edit)