Skip to main content

controller

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="https://unpkg.com/@mulsense/xnew@0.2.x/dist/xnew.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@tailwindcss/browser@4"></script>
</head>

<body class="relative m-0 p-0 w-full h-screen overflow-hidden">
<div id="main" class="relative w-full h-full"></div>
<script>
xnew('#main', (unit) => {
xnew(Box);
xnew(Controller);
});

function Controller(unit) {
// prevent default event
unit.on('touchstart contextmenu wheel', (event) => event.preventDefault());

xnew.nest('<div class="absolute left-0 right-0 bottom-0 w-full h-[30%]" style="container-type: size;">');

// left bottom
xnew('<div class="absolute left-0 top-0 bottom-0 w-[100cqh] h-full">', () => {
// directional pad
const dpad = xnew('<div class="absolute inset-[5cqh]">', xnew.basics.DirectionalPad, {});
dpad.on('-down -move -up', ({ vector }) => unit.emit('+move', { vector }));
});

// right bottom
xnew('<div class="absolute right-0 top-0 bottom-0 w-[100cqh] h-full">', () => {
// analog stick
const stick = xnew('<div class="absolute inset-[5cqh]">', xnew.basics.AnalogStick, {});
stick.on('-down -move -up', ({ vector }) => unit.emit('+move', { vector }));
});

// xnew(Gamepad);
}

function Box(unit) {
const box = xnew.nest('<div class="absolute w-48 h-48 inset-0 m-auto bg-blue-500">');
let current = { x: 0, y: 0, r: 0 };
let move = { x: 0, y: 0 };
let direction = +1;
unit.on('+move', ({ vector }) => move = vector);
unit.on('+action', () => direction *= -1);

unit.on('-update', () => {
current.x += move.x * 10;
current.y += move.y * 10;
current.r += direction;
box.style.left = current.x + 'px';
box.style.top = current.y + 'px';
box.style.transform = `rotate(${current.r}deg)`;
});
}
</script>
</body>

</html>