Movement And Controls (2024)

Movement And Controls

Click here to see this page in full context

The previous section of this Quick Start Guide gave some examples for drawing things to the screen, but just drawing things isn't much good if you can't also move them around... so in this section we'll be giving you some examples of movement for your objects, as well as some basic control schemes for different types of games. All the examples are given using GML Visual as well as the GML Code, so you can use whichever you feel more comfortable with. Note that we won't be explaining things in too much depth here, as we want you to get started making stuff as quickly as possible, so we encourage you to explore any links as you go along and to use the "search" function of the manual to look for additional information on anything you aren't sure about.

Before going any further, you might want to make a new project (either GML or GML Visual) from the Start Page, and add (or create) a few sprites as well as an object or two - as we'll be giving you some code that you can test using these - and make sure that the project has a room to place instances in. Don't worry too much about what the sprites you make look like, as even a simple white square will do, and once you'vegot everything ready you can start working on the examples listed below.

Move Towards The MouseMove Towards The Mouse

One of the simplest ways to get an object moving and interacting with the player is to use the mouse, and in this example we'll show you how to use some basic code to get an object to move towards wherever the user has clicked the left mouse button Movement And Controls (1).

To start with, open an object, assign it a sprite, and then give it a Global Left Mouse Down event:

Movement And Controls (2)

We use the global mouse events because they detect a click anywhere in the room, while the regular mouse events will only detect a click if the mouse actually clicks within the instance bounding box. In this event we want to add these actions or code:

Movement And Controls (3)

move_towards_point(mouse_x, mouse_y, 2);

Here we are telling the instance to move towards a position on the screen, in this case the "mouse_x" and "mouse_y" position ("mouse_x" and "mouse_y" are built-in variables that always hold the current mouse cursor position). The GML Visual does this by setting the "direction"and " speed"Instance Variables, while the GML does this using the function move_towards_point()(this also sets the speed and direction variables, just in a single, easy to use function).

Place an instance of this object in a room and then hit the Play button Movement And Controls (4), then click Movement And Controls (5) around the room to make the instance move towards the mouse:

Movement And Controls (6)Great! The instance of the object now moves towards where you clicked, and if you hold down the button, the instance will just keep following the mouse cursor. However, there is a problem... After you click once and release, the instance will keep on moving and eventually leave the room! There are a number of ways that we can fix this, and which one you choose will depend on what you want to do, but the easiest fix for now is to simply add a Global Mouse Button Released event, so add that now to the object and give it this code:

Movement And Controls (7)

speed = 0;

With this, the instance will only follow the mouse cursor for as long as the mouse button is held down, and when you release the button it will stop moving. Press Play Movement And Controls (8) and test it now.

Before we leave this example, there is one final issue that we need to resolve... If you click and hold the mouse button, but don't move the cursor, then the instance will move towards the cursor and then "vibrate" around it. This is because the instance is moving faster than 1 pixel at a time and so "over-shoots" the position and then tries to move back, and then over-shoots again, etc... (make the movement speed 5 or something like that to see the issue if it's not immediately obvious).

Movement And Controls (9)To solve this we need to add a Step Event to the object with this code:

Movement And Controls (10)

var _dist = point_distance(x, y, mouse_x, mouse_y);

if (_dist <= speed)
{
speed = 0;
}

Here we just check the distance from the instance to the mouse position, and if it's the same as or less than the current speed, we set the speed to 0. This makes the instance stop when it's close enough to the mouse position, and we don't get that nasty "vibrating" issue.

4-Way and 8-Way Movement With The Keyboard4-Way and 8-Way Movement With The Keyboard

Right at the start of this guide, we showed you the following action and code to move an instance to the right by two pixels every game step:

Movement And Controls (11)

x = x + 2;

This type of movement is called positional movement, as we are essentially picking up the instance and placing it down again at a new position every time the code is run. What we're going to do in this example is show you how to use this type of movement to move an instance around in 4directions:up, down, left and right.

To start with, open an object and assign it a sprite. Now, we could add in various Keyboard Events at this point, and in each one have the instance move in the desired direction, however, we only want the player to be able to move in one direction at a time and doing this with only the keyboard eventsis a bit more complicated than doing it using code. Instead we'll be using the Step Event - which you should add now to the object - with the following actions or code to use the Arrow Keys to move:

Movement And Controls (12)

if (keyboard_check(vk_left))
{
x = x - 2;
}
else if (keyboard_check(vk_right))
{
x = x + 2;
}
else if (keyboard_check(vk_up))
{
y = y - 2;
}
else if (keyboard_check(vk_down))
{
y = y + 2;
}

We are using an " if... else if... else if..." structure to ensure that the instance will only move in one direction at a time, and so the instance should only be able to move up, down, left or right, but not diagonally. Place an instance of the object in a room and press the Play button Movement And Controls (13) to test it now! If all has gone correctly, you should have something like this:

Movement And Controls (14)

We can modify this code to convert the 4-way movement into 8-way movement easily too... simply remove the " else" commands from the code blocks so that everything looks like this:

Movement And Controls (15)

if (keyboard_check(vk_left))
{
x = x - 2;
}
if (keyboard_check(vk_right))
{
x = x + 2;
}
if (keyboard_check(vk_up))
{
y = y - 2;
}
if (keyboard_check(vk_down))
{
y = y + 2;
}

Now when you press the Play button Movement And Controls (16) it'll look something like this:

Movement And Controls (17)

One final thing that's worth noting for users coding with GML... When using the GML Visual you can select the keyboard key that you want to use from a drop down list, but with GML it's not that simple. There are a number of Keyboard Constantsthat you can use - like the arrow key constants shown in the code above - but there are no constants for the alpha-numeric keys. These are handled slightly different, and require you to use the function ord(). The code below shows you how this would work using WASD instead of the arrow keys:

if (keyboard_check(ord("A")))
{
x = x - 2;
}
if (keyboard_check(ord("D")))
{
x = x + 2;
}
if (keyboard_check(ord("W")))
{
y = y - 2;
}
if (keyboard_check(ord("S")))
{
y = y + 2;
}

Gamepad MovementGamepad Movement

We've covered mouse movement and keyboard movement, so that means it's time to cover gamepad movement. Now, we won't be covering the d-pad, as really that works just like using the keyboard (simply change the keyboard functions in the above example for gamepad_button_check()or If Gamepad button Down), so in this example we'll look at using the analog stick for movement.

To start with, we need to detect the gamepad being used. Gamepads are given an ID value from 0 to 11, so we will use a " for" loop to detect the ID of any connected gamepads and store this ID value in a variable for future use. Since we only want to setect the first gamepad that is connected and not all of them, we will use the " break" command after we detect a gamepad so that the it "breaks" the loop (for example, if the first gamepad connected is ID 4, then the loop will only run 5 times, checking the ID values 0 - 4 and then breaking out of the loop when the gamepad is encountered). So, make (or open) an object, assign it a sprite, and then add a Create Event with the following:

Movement And Controls (18)

gamepad_id = -1;

for (var i = 0; i < 12; i += 1;)
{
if (gamepad_is_connected(i))
{
gamepad_id = i;
gamepad_set_axis_deadzone(gamepad_id, 0.2);

break;
}
}

Notice that in the above code we set the deadzonefor the gamepad. This is because analog sticks on different makes of gamepads will have different sensibility, and sometimes they can be so sensitive that if you don't set a deadzone then they can cause unwanted movement in your games. So we set the deadzone to a value like 0.2 to tell GameMaker to ignore any gamepad stick values under that absolute value.

To add the actual movement, we'll need a Step Event, so add that now and give it the following GML Visual or GML:

Movement And Controls (19)

if (gamepad_id > -1)
{
var _h = gamepad_axis_value(gamepad_id, gp_axislh);
var _v = gamepad_axis_value(gamepad_id, gp_axislv);
x += _h * 4;
y += _v * 4;
}

Here we are checking the left stick for horizontal or vertical movement. The axis functions return a value between -1 and 1, so for the horizontal axis -1 is left, 0 is not moving and 1 is right, and for the vertical axis it's -1 for up, 0 for not moving and 1 for down. Note too that the values are between -1 and 1, so - for example - the horizontal axis could return a value of 0.5, meaning the stick is halfway between the "rest" position and fully pushed to the right. For that reason, we then multiply the value by 4 (you can multiply by any value really, depending on the speed you want the instance to move) - it means that the speed of the instance will vary depending on how much of a movement has been made on the stick axis.

Place an instance of this object in a room and pres the press Play button Movement And Controls (20), then move around using the left stick of your connected gamepad. You should see something like this:

Movement And Controls (21)

Advanced 8-Way MovementAdvanced 8-Way Movement

In this final example, we're going to re-visit our 8-way movement code and address an issue it has, which is that diagonal movement is actually faster than up/down/left/right movement. This is simply because when moving diagonally, you are moving along the hypotenuse of a right-angled triangle created by the x/y movement values:

Movement And Controls (22)

To make it clearer what's happening, let's remove all the text and sprites and simply show the same line of movement roated 45° so it's horizontal:

Movement And Controls (23)

As you can see, the difference is pretty obvious, and if the instance moves more than 1 or 2 pixels per step, then it becomes very noticiable that diagonal movement is much faster! So how do we limit this? There are a number of ways to go about this, but we're going to concentrate on just one of them, because it introduces a couple of functions and concepts that will be useful to you later on in your games.

To deal with this, we are going to have to store the input values from the keys pressed independently in variables, and then check them and move according to the combination of keys that have been pressed. So, for this you'll need an object with a sprite assigned, and you'll need to give it a Step Event with the following actions or code:

Movement And Controls (24)

NOTEWe've split the Visual actions above over two columns to make it easier to visualise, but in the Visual editor, it will be placed consecutively.

var _left = keyboard_check(vk_left);
var _right = keyboard_check(vk_right);
var _up = keyboard_check(vk_up);
var _down = keyboard_check(vk_down);
var _hspd = _right - _left;
var _vspd = _down - _up;

We'll need to add some more code to actually move, but before we do, let's just explain this a bit. We want to convert left/right/up/down into equivalent horizontal and vertical speed values, so to do that we are getting the value of each key and then doing some basic maths on it to get the speed values. This works because if a key is being pressed then the check action or function will return "1", and if it's not being pressed, then the function will return 0. So, if - for example - right is being pressed, you have "1 - 0 = 1" for the " _hspd", and if left is being pressed you have "0 - 1 = -1" for the " _hspd" (and if they both get pressed then it's "1 - 1 = 0", so the instance won't move). Remember, in a GameMaker room, to move right we add to the x position and to move left we subtract, so this code will give us a positive or negative value that we can add or subtract to move horizontally or vertically depending on the keyboard input.

Now we can add the code that actually moves the instance, so - still in the Step Event, and after the above code - add this:

Movement And Controls (25)

if (_hspd != 0 || _vspd != 0)
{
var _spd = 4;
var _dir = point_direction(0, 0, _hspd, _vspd);
var _xadd = lengthdir_x(_spd, _dir);
var _yadd = lengthdir_y(_spd, _dir);
x = x + _xadd;
y = y + _yadd;
}

The above code first checks to see if one of two expressions is true, ie: if the horizontal or vertical speed variables are not 0. Note how the " if" GML check uses the symbol " ||". This means " or" when programming, so - in plain language - you are checking

if the variable _hspd does not equal zero
or
if the variable _vspd does not equal zero

You can string multiple expressions together in " if" checks in this way, and there are multiple different ways those expressions can be evaluated (for more information please see the section on Expressions here).

The next section of code stores a value for theactual movement speed in a variable and then gets a direction using the _hspd and _vspd values, which can be -1, 0, or 1. The direction function checks from (0, 0) as we aren't using room coordinates, and instead we want it to evaluate as a direction from 0° to 360° based on the variable values. The following diagram illustrates what's happening better than trying to explain it in words:

Movement And Controls (26)

NOTEDirection in GameMaker is calculated counter clockwise, so 0° and 360°areto the right, 90° is up, 180° is to the left and 270° is down.

Finally, we use the lengthdir_x()and lengthdir_y()functions to actually move the variable. These are vectorfunctions that take a length (distance) and a direction and then calculate the new position on the given axis based on these values (see the function descriptions for a more in-depth explanation).

That's a lot to take in at once, and don't worry if you don't quite understand it all! You will in time! All that's left to do now is add an instance of this object to a room, and then press the Play button Movement And Controls (27), and you should get silky-smooth 8 way movement without any of the issues related to moving diagonally:

Movement And Controls (28)

With these examples -and the previous ones for drawing -we hope that you've got enough of an understanding to start making your own projects! The last page of this Quick Start Guide contains a summary of some of the things you've learned as well as links to additional learning materials.

Back:GameMaker Manual Index

Next:Summary

© Copyright YoYo Games Ltd. 2024 All Rights Reserved
Movement And Controls (2024)

FAQs

Movement And Controls? ›

Movement control refers to the coordination of neural pathways to orchestrate complex patterns of muscular contractions, as seen in activities like playing sports, musical instruments, or dancing. It involves the integration of various motor units to achieve smooth and precise movements.

What is the meaning of movement control? ›

Movement Control can be defined as the ability of the nervous system to control the contraction of the muscles. There are multiple stages of movement control which include intent, planning, programming and execution of the movement.

What is the movement control theory? ›

Motor Control Theories include the production of reflexive, automatic, adaptive, and voluntary movements and the performance of efficient, coordinated, goal-directed movement patterns which involve multiple body systems (input, output, and central processing) and multiple levels within the nervous system.

What controls the movement of the body? ›

The brain, situated in the cranial cavity is an important internal organ. It is the control centre of our body. It controls the movements and all that we do.

What is neurological control of movement? ›

The foundation of neural control of movement is formed by the motor neurons. Motor neurons are the only cells in the CNS capable of directly activating muscles. Thus, the motor neurons forms them the final common path of neural activity, as proposed by the English neuroscientist Sir Charles Sherrington [4].

What are movement controls? ›

Movement control refers to the coordination of neural pathways to orchestrate complex patterns of muscular contractions, as seen in activities like playing sports, musical instruments, or dancing. It involves the integration of various motor units to achieve smooth and precise movements.

What are the 4 types of movement? ›

The four types of motion are:
  • linear.
  • rotary.
  • reciprocating.
  • oscillating.

What is an example of movement control? ›

An example of fine motor control is picking up a small item with the index finger (pointer finger or forefinger) and thumb. The opposite of fine motor control is gross (large, general) motor control. An example of gross motor control is waving an arm in greeting.

How do you control movement? ›

We can break this process down into three basic steps: 1) planning, 2) initiation, and 3) execution. The first two steps are mainly controlled by different areas of the cerebral cortex and the last step involves relaying the command from the CNS through the PNS to the muscles involved in the movement.

How do we control movement? ›

Voluntary muscles are controlled by the motor cortex, while involuntary muscles are controlled by other regions of the brain such as the hypothalamus.

What organ controls movement? ›

The cerebellum — also called the "little brain" because it looks like a small version of the cerebrum — is responsible for balance, movement, and coordination.

Who controls the movement? ›

The cerebellum is responsible for far more than coordinating movement. New techniques reveal that it is, in fact, a hub of sensory and emotional processing in the brain.

What controls the movement and balance? ›

The cerebellum is located behind the brain stem. While the frontal lobe controls movement, the cerebellum “fine-tunes” this movement. This area of the brain is responsible for fine motor movement, balance, and the brain's ability to determine limb position.

What brain disorder causes uncontrollable movements? ›

Parkinson's disease: Parkinson's disease is a brain disorder that causes unintended or uncontrollable movements and difficulty with balance and coordination.

What nerves control movement? ›

The spinal nerves help to control the function and movement of the rest of the body. The 31 pairs of spinal nerves include 8 cervical, 12 thoracic, 5 lumbar, 5 sacral, and 1 coccygeal. Their names match the adjacent spinal vertebra from which they exit.

What controls involuntary movements? ›

The medulla oblongata is the rod-shaped part of the brain which is seen below the cerebrum, located near the cerebellum of the brain. It controls involuntary actions like heartbeat and breathing.

What are the duties of movement control? ›

Monitors all activities related to the movement of cargo and personnel throughout the Mission area; Provides assistance and technical advice in all aspects of transportation, including goods requiring special handling. Advises Mission civilian personnel and Military/Police Contingents on all movement related matters.

What controls your movement? ›

Voluntary muscles are controlled by the motor cortex, while involuntary muscles are controlled by other regions of the brain such as the hypothalamus.

What are movement control exercises? ›

Introduction. Motor control exercise is a popular form of exercise that aims to restore co-ordinated and efficient use of the muscles that control and support the spine. The therapist guides the client to practice normal use of the muscles during simple tasks.

Top Articles
Bachelor of Science in Radiologic Sciences
Sonography Programs in Pembroke Pines FL - Sonography Prep
Craigslist Livingston Montana
Victor Spizzirri Linkedin
Christian McCaffrey loses fumble to open Super Bowl LVIII
What Are Romance Scams and How to Avoid Them
Blanchard St Denis Funeral Home Obituaries
Polyhaven Hdri
360 Training Alcohol Final Exam Answers
Puretalkusa.com/Amac
Giovanna Ewbank Nua
Craigslist Greenville Craigslist
Power Outage Map Albany Ny
Koop hier ‘verloren pakketten’, een nieuwe Italiaanse zaak en dit wil je ook even weten - indebuurt Utrecht
Shreveport Active 911
سریال رویای شیرین جوانی قسمت 338
Available Training - Acadis® Portal
Mail.zsthost Change Password
Niche Crime Rate
Vigoro Mulch Safe For Dogs
Kringloopwinkel Second Sale Roosendaal - Leemstraat 4e
Allybearloves
Ppm Claims Amynta
T Mobile Rival Crossword Clue
Reviews over Supersaver - Opiness - Spreekt uit ervaring
Naya Padkar Gujarati News Paper
Danielle Ranslow Obituary
How To Make Infinity On Calculator
Gina's Pizza Port Charlotte Fl
How does paysafecard work? The only guide you need
Ukg Dimensions Urmc
Deshuesadero El Pulpo
World Social Protection Report 2024-26: Universal social protection for climate action and a just transition
sacramento for sale by owner "boats" - craigslist
Stewartville Star Obituaries
Karen Wilson Facebook
Gopher Hockey Forum
Bunkr Public Albums
Cocaine Bear Showtimes Near Cinemark Hollywood Movies 20
Santa Clara County prepares for possible ‘tripledemic,’ with mask mandates for health care settings next month
Deepwoken: How To Unlock All Fighting Styles Guide - Item Level Gaming
Pink Runtz Strain, The Ultimate Guide
Advance Auto.parts Near Me
Port Huron Newspaper
Noga Funeral Home Obituaries
Here’s What Goes on at a Gentlemen’s Club – Crafternoon Cabaret Club
Ty Glass Sentenced
Evil Dead Rise - Everything You Need To Know
The 5 Types of Intimacy Every Healthy Relationship Needs | All Points North
Coleman Funeral Home Olive Branch Ms Obituaries
Immobiliare di Felice| Appartamento | Appartamento in vendita Porto San
Who We Are at Curt Landry Ministries
Latest Posts
Article information

Author: Dean Jakubowski Ret

Last Updated:

Views: 6307

Rating: 5 / 5 (50 voted)

Reviews: 89% of readers found this page helpful

Author information

Name: Dean Jakubowski Ret

Birthday: 1996-05-10

Address: Apt. 425 4346 Santiago Islands, Shariside, AK 38830-1874

Phone: +96313309894162

Job: Legacy Sales Designer

Hobby: Baseball, Wood carving, Candle making, Jigsaw puzzles, Lacemaking, Parkour, Drawing

Introduction: My name is Dean Jakubowski Ret, I am a enthusiastic, friendly, homely, handsome, zealous, brainy, elegant person who loves writing and wants to share my knowledge and understanding with you.