Establishing Variables in Blocks
Last updated
Last updated
You may not expect it, but there is a little bit of math that needs to be done to get our robot moving smoothly. But before we dive too deeply into that let's start with the basics of movement we'll need.
To start, create two variables x and y . This can be done within the Variable menu on the lefthand side.
For a quick reference let's take a look at what number each variable would be assigned at their far ends:
Joystick Direction |
|
|
0 | 1 | |
0 | -1 | |
-1 | 0 | |
1 | 0 |
Right now we have x and y assigned values based on our joystick's movement, but what does that mean? Why is that useful?
Maybe you have seen in a math class before something like this:
In this case, a is our variable that has been assigned some value. For this example, we can determine that value is 7. But what does that mean in programming?
Variables used in programming follow this same principle. We can define a variable within our code to hold a set value or a value that changes, such as we are doing here. Then whenever that variable is referenced the robot will read it as that assigned value!
So using our example above if I had:
My robot would know my variable of a is equal to 7 and therefore calculate the answer as 17 for me!
Consider for a moment, why should we use a variable when we could just use the number on its own?
We'll be using variables in greater detail in later sections, but even for our drive code you will be able to see the use of variables helps keep our program clean and easier to follow.
Once created, add the andblocks to the while loop above your existing power block.
Our y variable will be assigned as , which is the y-axis of the right joystick. Remember just like in Part 1: Programming a Motor with a Gamepad the y-axis will need to be inversed using the block available from the Math menu.
Next assign x as the , which is the x-axis of the right gamepad joystick. The x-axis of the joystick does not need to be inverted.
The and block sets assign values from the gamepad joystick to x and y. Depending on the orientation of the joystick, these valuables will receive some value between -1 and 1.
By using setting our variable at the beginning of our code we can inverse it without needing to do so every time we may reference the joystick's y-axis. Within a longer program, having our variables defined at the start would allow us to quickly change a value without having to hunt down or double check that every possible instance in the code has been updated to reflect this change. Instead we are able to change it once and continue testing!