// Turret Gun - Potentiometer and FSR // By Patrick Hebron import processing.serial.*; Serial myPort; Turret myTurret; BulletSystem myBulletSystem; int potVal = 0; int fsrVal = 0; void setup () { size(500, 500); myPort = new Serial(this, Serial.list()[0], 9600); myTurret = new Turret(width/2, height-40, 40); myBulletSystem = new BulletSystem(); } void draw () { background(120); myTurret.newPos(potVal, fsrVal); myTurret.display(); println("Potentiometer: " + potVal + " FSR: " + fsrVal); } void serialEvent (Serial myPort) { String serialIn = myPort.readStringUntil(10); if(serialIn != null) { String[] serialInPts = serialIn.split(","); if(serialInPts.length == 3) { potVal = int(serialInPts[0]); fsrVal = int(serialInPts[1]); } } } class Turret { float angle, emRate; float cX, cY; int x, y, radius; Turret(int X, int Y, int Radius) { x = X; y = Y; radius = Radius; } void newPos(int pot, int fsr) { angle = map(pot, 0, 1023, 0, 180); emRate = map(fsr, 0, 1023, 0, 255); cX = (radius * cos(radians(-angle)) + x); cY = (radius * sin(radians(-angle)) + y); if(emRate > 100) myBulletSystem.addBullet(cX, cY, (cX-x)/2, (cY-y)/2); myBulletSystem.run(); } void display() { stroke(0); fill(255); strokeWeight(2); ellipse(x, y, radius, radius); line(x,y,cX,cY); } } class BulletSystem { ArrayList bullets; BulletSystem() { bullets = new ArrayList(); } void run() { for(int i = bullets.size()-1; i >= 0; i--) { Bullet b = (Bullet) bullets.get(i); b.run(); if(b.dead()) { bullets.remove(i); } } } void addBullet(float px, float py, float dx, float dy) { bullets.add(new Bullet(px,py,dx,dy)); } } class Bullet { float xPos, yPos; float xDir, yDir; int timer; Bullet(float XPos, float YPos, float XDir, float YDir) { xPos = XPos; yPos = YPos; xDir = XDir; yDir = YDir; timer = 25; } void run() { update(); render(); } void update() { xPos += xDir; yPos += yDir; timer--; } void render() { noStroke(); int opacity = int(map(timer,0,25,0,255)); fill(255,0,0,opacity); rect(xPos,yPos,2,2); } boolean dead() { if (timer <= 0.0) return true; else return false; } }