VirtualJoystick based on AdvancedDynamicTexture

I implemented VirtualJoystick based on AdvancedDynamicTexture, using TypeScript, playground: https://www.babylonjs-playground.com/#4A1OSE#4

Originally inspired by: https://www.babylonjs-playground.com/#C6V6UY#547

3 Likes

@MakarovDs777 You can also see:

AdvancedDynamicTexture is just a 2-dimensional UI element, and the VirtualJoystick implementation based on it currently only abstracts the amount of movement change in the x and z dimensions. The current implementation distinguishes between left and right Joysticks by defining the identifiers xAddPosition, yAddPosition, and yAddRotation, xAddRotation, a total of four variables, perhaps renamed leftHorizontalMovement, leftVerticalMovement and rightHorizontalMovement, rightVerticalMovement. Be more “name-aware” (When you see the naming, you know the meaning).
How to apply those 4 variables depends on your business code, it can be character control or camera control.
For the code in https://www.babylonjs-playground.com/#4A1OSE#4, the naming isn’t good because it’s not accurate. But the main structure is as follows.

class JoystickState Joystick class, hold the Joystick values

  • xAddPosition: number The value of horizontal movement on the left side of the Joystick.
  • yAddPosition: number The value of vertical movement on the left side of the Joystick.
  • xAddRotation: number The value of horizontal movement on the right side of the Joystick.
  • yAddRotation: number The value of vertical movement on the right side of the Joystick.
  • JoystickLeft() left Joystick logic
  • JoystickRight() right Joystick logic

The Joystick usage code is simple:

// create
let adt = BABYLON.GUI.AdvancedDynamicTexture.CreateFullscreenUI("UI")
let state = new JoystickState(adt)
// use either the left or right Joystick, either one or both.
state.JoystickLeft()
state.JoystickRight()
// use the values
scene.registerBeforeRender(function () {
    console.log(`left: horizontal=${state.xAddPosition}, vertical=${state.yAddPosition}`)
    console.log(`right: horizontal=${state.xAddRotation}, vertical=${state.yAddRotation}`)
})

Add VirtualJoystick to Pryme8’s Sprite Character Controller demo(https://playground.babylonjs.com/#N2BK7Q#46) to support touch devices.