xxxxxxxxxx
106
// Initialize variables
let dino;
let obstacles = [];
let score = 0;
let forceSensorValue = 0;
let jumpThreshold = 500; // Adjust this threshold based on your sensor readings
function setup() {
createCanvas(600, 400);
dino = new Dino();
}
function draw() {
background(255);
dino.show();
dino.move();
if (frameCount % 60 == 0) {
obstacles.push(new Obstacle());
}
for (let i = obstacles.length - 1; i >= 0; i--) {
obstacles[i].show();
obstacles[i].move();
if (obstacles[i].hits(dino)) {
console.log("Game over");
noLoop();
}
if (obstacles[i].offscreen()) {
obstacles.splice(i, 1);
score++;
}
}
textSize(32);
text("Score: " + score, 10, 30);
// Read force sensor value from serial port
if (serial.available() > 0) {
forceSensorValue = serial.read();
console.log(forceValue); // log force sensor value to console
if (forceSensorValue > jumpThreshold) {
dino.jump(); // call jump function if force sensor value is above 50
}
}
}
class Dino {
constructor() {
this.x = 50;
this.y = height - 50;
this.width = 50;
this.height = 50;
this.velocity = 0;
this.gravity = 1;
}
show() {
fill(0);
rect(this.x, this.y, this.width, this.height);
}
move() {
this.y += this.velocity;
this.velocity += this.gravity;
this.y = constrain(this.y, 0, height - this.height);
}
jump() {
if (this.y == height - this.height) {
this.velocity = -20;
}
}
}
class Obstacle {
constructor() {
this.x = width;
this.y = height - 50;
this.width = 20;
this.height = 50;
this.velocity = 5;
}
show() {
fill(255, 0, 0);
rect(this.x, this.y, this.width, this.height);
}
move() {
this.x -= this.velocity;
}
hits(dino) {
return collideRectRect(this.x, this.y, this.width, this.height, dino.x, dino.y, dino.width, dino.height);
}
offscreen() {
return this.x < -this.width;
}
}
function keyPressed() {
if (key == " ") {
// important to have in order to start the serial connection!!
setUpSerial();
}
}