Skip to content

Instantly share code, notes, and snippets.

@theapi
Last active May 31, 2022 16:02
Show Gist options
  • Save theapi/7038786 to your computer and use it in GitHub Desktop.
Save theapi/7038786 to your computer and use it in GitHub Desktop.
Websocket with the virtual joystick Uses WebSocket-for-Python (CherryPy) & https://github.com/jeromeetienne/virtualjoystick.js
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
<script type='application/javascript' src='https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js'></script>
<script type='application/javascript'>
$(document).ready(function() {
websocket = 'ws://127.0.0.1:9000/ws';
if (window.WebSocket) {
ws = new WebSocket(websocket);
}
else if (window.MozWebSocket) {
ws = MozWebSocket(websocket);
}
else {
console.log('WebSocket Not Supported');
return;
}
window.onbeforeunload = function(e) {
$('#wsresponse').val('Bye bye...\n');
ws.close(1000, 'Bye');
if(!e) e = window.event;
e.stopPropagation();
e.preventDefault();
};
ws.onmessage = function (evt) {
$('#wsresponse').val(evt.data);
};
ws.onopen = function() {
ws.send("0,0");
};
ws.onclose = function(evt) {
$('#wsresponse').val('Connection closed by server: ' + evt.code + ' "' + evt.reason + '"\n');
};
});
</script>
<style>
body {
overflow : hidden;
padding : 0;
margin : 0;
background-color: #BBB;
}
#info {
position : absolute;
top : 0px;
width : 100%;
padding : 5px;
text-align : center;
}
#info a {
color : #66F;
text-decoration : none;
}
#info a:hover {
text-decoration : underline;
}
#container {
width : 100%;
height : 100%;
overflow : hidden;
padding : 0;
margin : 0;
-webkit-user-select : none;
-moz-user-select : none;
}
</style>
</head>
<body>
<div id="container"></div>
<div id="info">
<form action='#' id='chatform' method='get'>
<label for='send'>Send: </label><input type='text' id='send' />
<label for='wsresponse'>Socket response: </label><input type='text' id='wsresponse' />
</form>
<span id="result"></span>
</div>
<script src="virtualjoystick.js"></script>
<script>
console.log("touchscreen is", VirtualJoystick.touchScreenAvailable() ? "available" : "not available");
var joystick = new VirtualJoystick({
container : document.getElementById('container'),
mouseSupport : true
});
setInterval(function(){
$msg = joystick.deltaX() + ',' + joystick.deltaY();
if ($('#send').val() != $msg) {
$('#send').val($msg);
ws.send($msg);
}
var outputEl = document.getElementById('result');
outputEl.innerHTML = '<b>Result:</b> '
+ ' dx:'+joystick.deltaX()
+ ' dy:'+joystick.deltaY()
+ (joystick.right() ? ' right' : '')
+ (joystick.up() ? ' up' : '')
+ (joystick.left() ? ' left' : '')
+ (joystick.down() ? ' down' : '');
}, 1/30 * 1000);
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment