Customizable On-screen Joystick

Playroom includes a customizable on-screen joystick controller that can be used by players as input. It also supports additional buttons that can be used for actions such as jumping, shooting, etc.

Here is a usage example, check out the API Docs for more details:

 
import { insertCoin, myPlayer, onPlayerJoin, Joystick } from 'playroomkit';
 
// Start the game
await insertCoin();
 
let players = [];
// Create a joystick controller for each joining player
onPlayerJoin((state)=>{
  // Joystick will only create UI for current player (myPlayer)
  // For others, it will only sync their state
  const joystick = new Joystick(state, {
    type: "dpad",
    buttons: [
      {id: "jump", label: "Jump"}
    ]
  });
  players.push({state, joystick});
})
 
// In your game loop
players.forEach(({state, joystick})=>{
  // Update player position based on joystick state
  const dpad = joystick.dpad();
  if (dpad.x === "left"){
    // move player left
  }
  else if (dpad.x === "right"){
    // move player right
  }
 
  // Check if jump button is pressed
  if (joystick.isPressed("jump")){
    // jump
  }
});
 

Here are a few examples of the joystick UI:

D-Pad

Angular with Buttons

Angular with Button and Zone

FAQs

I want angular value as 0-360 degrees

You can convert radians to degrees and then add 90 to get the value in degrees.

function radToDeg(rad){
  return rad * 180 / Math.PI + 90;
}
 
console.log(radToDeg(joystick.angle()));

I want to convert angular value to X, Y components that go between -1 and 1

You can use Math.cos and Math.sin to get the X and Y components.

function radToXY(rad){
  return {
    y: Math.cos(rad),
    x: Math.sin(rad)
  };
}
 
console.log(radToXY(joystick.angle()));