xxxxxxxxxx
136
let spritesheet;
let timer = 1000;
//let nextRun = timer;
let horses = [];
let rval = 0;
let step = 0;
let speed = 5;
let counter = 0;
let bg = [];
let right = false;
let left = false;
let serial;
let run = false;
let xPos;
let zPos;
let prevVal = 0;
let direction = 1;
let baseReading = 120;
let fromArduino = [];
function preload() {
spritesheet = loadImage("horse_final_run.png");
soundBG = loadSound("tugan_zher.mp3");
for (let i = 1; i < 21; i++) {
bg.push(loadImage(str(i) + "bg.jpg"));
}
}
function setup() {
createCanvas(800, 580);
// soundBG.loop();
soundBG.setVolume(0.5);
let w = spritesheet.width;
let h = spritesheet.height / 7;
for (let y = 0; y < 7; y++) {
for (let x = 0; x < 1; x++) {
horses.push(spritesheet.get((x * w) / 7, y * h, w, h));
}
}
setUpSerial();
}
function keyPressed() {
if (key == "a") {
setUpSerial(SELECT_PORT);
}
}
function draw() {
background(255);
console.log(frameRate());
///image(bg[int(map(rval - 1, 0, 1023, 0, 20))], 0, 0);
// counter = (counter + 10)%width;
// image(horses[step], counter, 420);
let currentTime = millis()%75;
if (currentTime < timer) {
step = (step + 1) % 7;
}
timer = currentTime;
push();
imageMode(CENTER);
translate(width / 2, 420);
if (left) scale(-1, 1);
image(horses[step], 0, 0);
pop();
// xPos = fromArduino[0];
print(fromArduino)
if (xPos == null) {
print("waiting for sensor...");
} else {
print(baseReading + " " + xPos);
print(left + " " + right);
// if (xPos != prevVal) {
// if (xPos < 160 && xPos >10) {
// if ( xPos < baseReading - 15) {
// right = true;
// counter = 0;
// } else if (xPos > baseReading + 15 ) {
// left = true;
// counter = 800;
// }
// prevVal = xPos;
// } else {
// right = left = false;
// }
// }
}
}
function readSerial(data) {
////////////////////////////////////
//READ FROM ARDUINO HERE
////////////////////////////////////
if (data != null) {
// make sure there is actually a message
// split the message
fromArduino = split(trim(data), ",");
// // if the right length, then proceed
// if (fromArduino.length == 3) {
// xPos = fromArduino[0];
// zPos = fromArduino[1];
// rval = fromArduino[2];
// // print(xPos + "," + zPos + "," + rval);
// }
//////////////////////////////////
//SEND TO ARDUINO HERE (handshake)
//////////////////////////////////
let sendToArduino = "\n";
writeSerial(sendToArduino);
}
}