Combined controller support with serial connection

This commit is contained in:
sam
2023-11-24 14:13:04 +01:00
parent 26965fc6af
commit 0c5a5142e7

View File

@@ -1,3 +1,75 @@
let port;
let reader;
const decoder = new TextDecoder("utf-8");
let readibleoutput = 0;
let booleanArray = [];
// Request a port and open a connection.
async function connect() {
//vraag aan de browser om een serial port te selecteren
port = await navigator.serial.requestPort();
await port.open({ baudRate: 9600 });
reader = port.readable.getReader();
console.log("Port is open!");
readLoop()
}
// Read data from serial port
async function readLoop() {
let buffer = [];
// loop until reader.cancel() is called
while (true) {
// Wait for data
const { value, done } = await reader.read();
for (let iByte = 0; iByte < value.length; iByte++) {
let singleByte = value[iByte];
//functie maken er van met boolean!!!
if (singleByte != 10) {
buffer.push(singleByte);
}
else {
let sensorString = decoder.decode(new Uint8Array(buffer));
//Put all data in a json Array and parse it to a boolean array
try {
// Parse the incoming data as JSON
// "replace(/'/g, '\"')" replaces all single quotes with double quotes with use of regular expressions. So we can use Jsonparse to parse it into a booleanArray
let SerialArray = JSON.parse(sensorString.replace(/'/g, '"'));
// Ensure SerialArray is an array
if (Array.isArray(SerialArray)) {
//Convert the array of strings to a boolean array
//When a bit is 1 it becomes true, when a bit is 0 it becomes false
booleanArray = SerialArray.map(bit => bit == '1');
console.log(booleanArray);
} else {
console.error("Dit is geen Array");
}
} catch (e) {
console.log("json niet geparserd");
}
Movementloop()
buffer = [];
}
if (done) {
console.log('[readLoop] DONE', done);
reader.releaseLock();
break;
}
}
}
}
// Sluit de poort
async function disconnect() {
await reader.cancel();
await port.close();
console.log("Port is closed!");
}
//--------------------Game--------------------
let Playerposx = 500;
let Playerposy = 300;
const size = 10; const size = 10;
radius = size/2; radius = size/2;
cirX = 500 cirX = 500
@@ -15,6 +87,7 @@ function setup() {
createCanvas(width, height); createCanvas(width, height);
frameRate(120); frameRate(120);
// disable the outline of shapes // disable the outline of shapes
Movementloop()
noStroke(); noStroke();
} }
@@ -33,6 +106,18 @@ function keyPressed() {
} }
} }
async function Movementloop() {
if (booleanArray[1]) {
Playerposx += 2;}
if (booleanArray[3]) {
Playerposx -= 2;}
if (booleanArray[2]) {
Playerposy += 2;}
if (booleanArray[0]) {
Playerposy -= 2;}
}
function object_collision() { function object_collision() {
var squareCenterX = squareX + squareSize / 2; var squareCenterX = squareX + squareSize / 2;
var squareCenterY = squareY + squareSize / 2; var squareCenterY = squareY + squareSize / 2;