Virtual Joysticks for User Input
-
Introduciton
You can now add joystick-style user controls for your 3D games, which is a natural input method for users on touchpads and smartphones.
Note that this new feature only works in 3D projects, and a 3D scene must be initialized first.
Add a Joystick
A virtual joystick is made of 2 parts:
- A “base” that is composed of 2 circles. Whenever the pointer is pressed down, the base will not move as the pointer is dragged around it.
- A “puck” that is a smaller circle with a dot at its center. It shows the current position of the pointer relative to the base.
You can add a new joystick using the following block:
The inputs are:- Left or Right: you can add a left or right joystick using this block. The left one only covers the left half of the screen, and the right one only covers the right half. Use this block 2 times to add both joysticks.
- Color1 and Color2: These two color inputs control the colors of the base and the puck.
- Scale: This is a scaling factor that controls the size of the virtual joystick. By default, it is 100, which means 100% of the default size. If you would like to double the size of the joystick, you can set this value to 200.
Read joystick properties
You can read the properties of a joystick using this reporter block:
It has 2 inputs:- Side: left or right
- Property:
- x or y: the position of the puck relative to the center of the base. Note that both x and y are between -1 and 1. For example, if the puck is at the right edge of the base, then x will be 1 and y will be 0.
- dir: the direction of the puck relative to the base in degrees, which is between -180 and 180.
- Distance: the distance of the puck from the base between 0 and 1.
- pressed: whether the joystick is pressed down. 0 means not pressed down, and 1 means it is pressed down. This should be the first value to check, since if the joystick is not pressed down, then all the other properties are not valid.
Remove all joysticks
You can use this block to remove all the joysticks you have added so far:
Demo
In this demo program, we first add a 3D glass object, then add 2 virtual joysticks of different colors and scales. Then we enter a forever loop: whenever the left or right joystick is pressed down, we read its properties into a few variables, and also rotate the 3D glass based on the “dir” property:
Here is the project link: