Howdy, Stranger!

We are about to switch to a new forum software. Until then we have removed the registration on this forum.

  • How to connect two or more things in one array

    I think you need a pre-loop to set all the circles to non-overlapping and then a nested loop to set the overlapping ones to the overlapping colour, you can't just have an else statement inside the nested loop.

    Why not? Say you have three circles. The first two overlap, so you set them as overlapping. You then check them both against circle 3 and neither overlap with circle 3 so you set them both as non-overlapping...

  • How to connect two or more things in one array

    You store your circles in an array. You are not comparing the circles against each other. So you have:

      for (int j, i = 0; i < p.length; i++) {
        p[i].display();
        p[i].mouseOver();
      }
    

    You need instead

    void draw() {
      background(0);
    
      if(p.length>1){  //Need to have more than 1 to check overlap
        for (int i = 0; i < p.length; i++) {   
          for (int other = i; other < p.length; other++) {
            boolean res=p[i].overlapOtherCircle(p[other]);  
    
             if(res==true){
                  //Overlap happened: Change the color of both the 'i' and 'other' object
             }
            else{
                //Update the field of only i object with a non-overlapping color
            }
          }  
        }
      }
    
      for (int i = 0; i < p.length; i++) {
        p[i].display();    
      }
    }
    

    and inside your class you need to define:

    boolean overlapOtherCircle(Postac  otherObj){
       return dist(x,y,otherObj.x,otherObj.y)  >  (radius/2.0 + otherObj.radius/2.0);
    }
    

    Check this

    www.jeffreythompson.org/collision-detection/index.php
    https://forum.processing.org/two/discussion/24966/bouncing-balls-collision#latest

    Notice there is a new forum at https://discourse.processing.org

    Kf

  • drag & drop images in Processing

    Hi, I am trying to make a window where it is possible to drag and drop different images and to make them overlap with a mouse click. Found a perfect example for it in openprocessing: https://www.openprocessing.org/sketch/540720 but I guess it would only work in p5.js

    In processing library there are some examples of dragging the pictures, but they do so without mouse click and it is not possible to drop them. So I am wondering, is there any advanced example of drag & drop img that can run in Processing, or I better have to download this p5.js?

    Cheers, tija

  • Per-pixel collision with arrays

    Took the code a lot further, it runs multiple pipes and the collision pgraphic is minimally sized for speed.

    For me, I go from 1000fps to ~600fps when checking for collision;

    FX2D runs much faster but is more limited, holds at 1000fps for me. To convert replace P2D with FX2D on line 12 and remove the P2D 3rd argument entirely on line 53.

    color blue = color(0, 0, 255, 255), 
      transparent = color(0, 0, 0, 0);
    
    PImage pipe = loadImage("http://" + "flappycreator.com/default/tube2.png");
    PImage bird = loadImage("http://" + "flappycreator.com/default/bird_sing.png");
    
    Sprite sbird;
    ArrayList<Sprite> spipes;
    float fps = 0;
    
    void setup() {
      size(800, 800, P2D);
      //bird.resize((int)(bird.width*2), ((int)bird.height*2));
      spipes = new ArrayList<Sprite>();
      for (int i = 0; i < 6; i++) {
        Sprite sPipe = new Sprite(pipe, color(255, 0, 0, 200));
        sPipe.loc = new PVector(i*120+50, 500+random(250));
        spipes.add(sPipe);
      }
      sbird = new Sprite(bird, color(0, 255, 0, 200));
      frameRate(1000);
      noCursor();
    }
    
    void draw() {
      clear();
      sbird.loc = new PVector(mouseX,mouseY);
      sbird.draw();
      for (Sprite s : spipes) {
        s.draw();
        PixelCollision check = sbird.pixelCollision(s);
        if (check!=null) {
          image(check.pg, check.loc.x, check.loc.y);
          stroke(0,255,0,255);
          noFill();
          rect( check.loc.x, check.loc.y, check.pg.width, check.pg.height);
          noStroke();
          stroke(255);
          fill(255,0,255,255);
          ellipse(check.hit.x, check.hit.y, 5, 5);
        }
      }
      fill(255);
      fps = (fps*119 + frameRate)/120.0;
      text((int)fps + " fps", 10, 10);
    }
    
    class PixelCollision {
      PGraphics pg;
      PVector loc;
      PVector hit;
      PixelCollision(int w, int h, PVector nloc) {
        pg = createGraphics(w, h, P2D);
        loc = nloc.copy();
      }
    }
    
    class Sprite {
      PImage img;
      PVector loc = new PVector(0, 0);
      color tint;
      Sprite(PImage pimg, color colTint) {
        img = pimg;
        tint = colTint;
      }
    
      void draw() {
        draw(g);
      }
    
     boolean overlap(Sprite s) {
        if ((loc.x < s.loc.x+s.img.width) && (loc.x+img.width > s.loc.x) &&
          (loc.y < s.loc.y+s.img.height) && (loc.y+img.height > s.loc.y)) {
          return true;
        }
        return false;
      }
    
      void draw(PGraphics pg) {
        pg.pushMatrix();
        pg.translate(loc.x, loc.y);
        pg.image(img, 0, 0);
        //pg.rect(0, 0, bird.width, bird.height);
        pg.popMatrix();
      }
    
      PixelCollision pixelCollision(Sprite s) {
        PixelCollision pc = null;
        if (overlap(s)) {
    
          float x = max(loc.x, s.loc.x);
          float y = max(loc.y, s.loc.y);
          float w =  min(loc.x+img.width, s.loc.x+s.img.width);
          float h =  min(loc.y+img.height, s.loc.y+s.img.height);
    
          pc = new PixelCollision( ceil(w-x), ceil(h-y), new PVector(x, y));
          PGraphics pg = pc.pg;
          pg.beginDraw();
          pg.clear();
    
          pg.tint(tint);
          pg.image(img, -(x-loc.x), -(y-loc.y));
    
          pg.tint(s.tint);
          pg.image(s.img, -(x-s.loc.x), -(y-s.loc.y));
    
          pg.endDraw();
          pg.loadPixels();
          int i = 0;
          for (; i < pg.width*pg.height-1; i++) {
            color c = pg.pixels[i];
            if ((red(c)>0)&&(green(c)>0)) {
              //pg.pixels[i] = blue;
              break;
            }
          }
          if (i== pg.width*pg.height-1) pc.hit = null;
          else pc.hit = new PVector(x+ (i%pg.width), y + floor((i-(i%pg.width))/pg.width));
          /* for (; i < pg.width*pg.height; i++) { // uncomment this and above to show collisions, slows code
           color c = pg.pixels[i];
           if ((red(c)>0)&&(green(c)>0)) {
           pg.pixels[i] = blue;
           }
           }
           pg.updatePixels(); */
        }
        if ((pc != null) && (pc.hit == null)) return null;
        return pc;
      }
    }
    
  • Per-pixel collision with arrays

    Here's an example of some pixel based collision. Perhaps I should point out this way of doing it on the CPU is very slow and not really good for a commercial game, needs to be done in shaders.

    A solution to this might be to check for bounding box collisions, create a collision pgraphics that is only the size of the overlap (far less pixels), and draw your images there offset.

    Basically, you draw your image twice. Once to the screen, once tinted and transparent to a collision pgraphics. Then we check all the pixels in the collision pgraphics for pixels that contain both the bird(tinted to be only red) and the pipe(tinted to be only green).

    PGraphics pgCollision;
    color blue = color(0, 0, 255, 255),
          transparent = color(0,0,0,0);
    
    
    PImage pipe = loadImage("http://" + "flappycreator.com/default/tube2.png");
    PImage bird = loadImage("http://" + "flappycreator.com/default/bird_sing.png");
    
    void setup() {
      size(800, 800, P2D);
      pgCollision = createGraphics(width, height, P2D);
    }
    
    void draw() {
      clear();
    
      // draw tinted semi-transparent images
      pgCollision.beginDraw();
      pgCollision.clear();
      pgCollision.tint(255, 0, 0, 200); // draw bird as transparent red
      drawBird(pgCollision);
      pgCollision.tint(0, 255, 0, 200); // pipes as transparent green
      drawPipe(pgCollision);
      pgCollision.endDraw();
      noTint();
    
      // check all pixels for ones that contain both red and green
      pgCollision.loadPixels();
      for (int i = 0; i < width*height; i++) {
        color c = pgCollision.pixels[i];
        if ((red(c)>0)&&(green(c)>0))
          pgCollision.pixels[i] = blue; // collision detected
          else pgCollision.pixels[i] = transparent; // optional, slow
      }
      pgCollision.updatePixels();  
    
      drawPipe(g);
      drawBird(g);
      image(pgCollision, 0, 0);
    }
    
    void drawPipe(PGraphics pg) {
      pg.image(pipe, 200, 600);
    }
    
    void drawBird(PGraphics pg) {
      pg.image(bird, mouseX, mouseY);
    }
    
  • Per-pixel collision with arrays

    I'm fairly new to processing but I've been progressing well with learning how to use it. I've been working on a simple flappy bird esque game and what I want to do is to have the bird and "pipes" collisions be recognized on a pixel-level, ive seen Peter Lagers code for pp_collision but i can't seem to get it to work for the obstacles. can someone tell me how to incorporate the classes into pp_collision(PImage imgA, float aix, float aiy, PImage imgB, float bix, float biy)

    for souls https://i.imgur.com/PZm7ivN.png and https://i.imgur.com/wvOkeEZ.png . I would love to know how to get collisions on a pixel level for animated sprites (ie. the souls array) as well but its secondary which is why i commented its code out.

    //int numFrames = 2;  // The number of frames in the animation
    //int currentFrame = 0;
    //PImage[] souls = new PImage[numFrames];
    
    
    int gameState; //0 = startscreen, 1 = in-game, 2 = game over, 3 = restart-screen
    int o = 240;
    
    
    Ghost ghost;
    Obstacle[] obstacles = new Obstacle[2];
    Score score;
    // Game states
    boolean gameStarted = false;
    boolean gameOver = false;
    boolean gameRestart = false;
    
    
    void setup() {
      //frameRate(30);
      fullScreen(FX2D);
      //size(1280, 720, FX2D);
    
      ghost = new Ghost(width/2, height/2);
      obstacles[0] = new Obstacle(width, random(100, height-100));
      obstacles[1] = new Obstacle(width*1.5+25, random(100, height-100));
      score = new Score();
    
      //startTimer = new Timer (0);
    
      //for (int k = 0; k < numFrames; k++) {
       // String imageName = "Soul_" + nf(k, 2) + ".png";
       // souls[k] = loadImage(imageName);
      //}
    }
    
    
    void draw() {
      background(175); 
    
      if (gameState==0) {
        gameRestart = true;
        drawMenuScreen();
        score.highscores();
        //startTimer.countUp();
        //fill (255);
        //text (startTimer.getTime(), 60, 60);
      } 
      if (gameState==0 && mousePressed) {
        if (gameRestart == true)
          //timerReset();
        score.reset();
        gameState = 1;
      }
    
    
      if (gameState==1) { 
        gameStarted = true;
        gameRestart = false;
        ghost.draw();
        for (Obstacle o : obstacles) { 
          o.draw();
          //Souls();
        }
        score.draw();
        detectCollision();
    
        if (gameState==1 && mousePressed) {
          //startTimer.countUp();
          //fill (255);
          //text (startTimer.getTime(), 60, 60);
        }
        if (gameState==1 && mousePressed) {
          ghost.jump();
        }
      }
    
    
      if (gameState==2) {
        //startTimer.countUp();
        //fill (255);
        //text (startTimer.getTime(), 60, 60);
        gameStarted = false;
        gameRestart = false;
        drawGameOver();
        ghost.reset();
        for (Obstacle obs : obstacles) { 
          obs.reset();
        }
      }
      //if (gameState==2 && startTimer.getTime()>=3.5) {
      if (gameState==2 && mousePressed) {
        if (gameStarted == false && gameRestart == false);
        //timerReset();
        gameState=3;
      }
    
    
      if (gameState==3) {
        gameRestart = true;
        drawMenuScreen();
        score.highscores();
      } 
      if (gameState==3 && mousePressed) {  
        if (gameRestart == true)
          score.reset();
        gameState = 1;
      }
    }
    
    
    
    
    
    
     class Score {
      private int score = 0;
      private int highscore;
      private boolean scoreIncreased = false;
    
    // Methods for increasing scores. If score is NOT increased
    
      void highscores(){
        if (score>highscore)
          highscore=score;
          else if (gameState==0 || gameState==3) {
          textAlign(CENTER);
          fill(255);
          textSize(width/60);
          text("HIGHSCORE: " + highscore, width/2, height/2 + height/8.25);
        }  
      }
    
      void increase() {
        if (!scoreIncreased) {
          score += 1;
          scoreIncreased = true;
        }
      }
    
      void reset() {
        score = 0;
        scoreIncreased = false;
      }
    
      void allowScoreIncrease() {
        scoreIncreased = false;
      }
    
    
      void draw() {
        pushStyle();
        if (gameState==2) {
          textAlign(CENTER);
          fill(0);
          textSize(width/60);
          text("SCORE: " + score, width/2, height/2 + 65);
        } 
          else if (gameState==1) {
          //rectMode(CORNER);
          textAlign(CENTER);
          fill(255);
          textSize(width/60);
          text("Score: " + score, width/2, 40);
        }
        popStyle();
      }
    }
    
    
    
     class Obstacle {
      float initX;
      float topX;
      float topY;
      float w = 120; // original was 50
      PImage obstacle1, obstacle2;
    
      Obstacle(float initialTopX, float initialTopY) {
        initX = initialTopX;
        topX = initialTopX;
        topY = initialTopY;
        obstacle1 = loadImage("https://" + "i.imgur.com/9Dnn4sI.png");
        obstacle2 = loadImage("https://" + "i.imgur.com/d83OfMi.png");
      }
    
    
      void draw() {
        pushStyle();
        imageMode(CORNERS);
        image(obstacle1, topX, topY, topX+w, height-1);
        image(obstacle2, topX, 0, topX+w, topY - 180);
        popStyle();
    
         // Controls speed of object x movements (namely for obstacles)
        // topX -= 4.25;
        topX -= 9.5;
      }
    
      void reset() {
        topX = initX;
        topY = random(100, height-100);
      }
    
      void reposition() {
        topX = width;
        topY = random(100, height-100);
      }
     } 
    
    
    
    
    class Ghost {
      float x;
      float y;
      float size = 85;
      float vy = 0;
      float ay = 0.63;
      PImage ghost;
    
      Ghost(float initialX, float initialY) {
        x = initialX;
        y = initialY;
        ghost = loadImage("https://" + "i.imgur.com/GPRyMO7.png");
      }
    
      void draw() {
        pushStyle();
        imageMode(CENTER);
        image(ghost, x, y, size, size);
        popStyle();
    
    
        y += vy;
        vy += ay;
      }
    
      void reset() {
        y = 200;
        vy = 0;
      }
    
      void jump() {
        vy = -9.5;
      }
    }
    
    
    
    
    
    
    // void Souls(){   
    //   currentFrame = (currentFrame+1) % numFrames;  // Use % to cycle through frames
    //   image(souls[(currentFrame) % numFrames], width/2, height/2);
    //}
    
    
    
    
    void drawGameOver() {
      pushStyle();
      fill(200, 200, 200, 200);
      noStroke();
      rect(-20, -20, width + 40, height + 40);
      score.draw ();
      popStyle();
    }
    
    void drawMenuScreen() {
      fill(0);
      noStroke();
      rect(-20, -20, width + 40, height + 40);
      ;
    }
    
    
    
    void detectCollision() {
      // Did the ghost come out of the screen?
      if (ghost.y > height || ghost.y < 0) {
        gameState=2;
      }
    
      for (Obstacle obstacle : obstacles) {
        if (ghost.x - ghost.size/2.0 > obstacle.topX + obstacle.w) {
          score.increase();
        }
    
        if (obstacle.topX + obstacle.w < 0) {
          obstacle.reposition();
          score.allowScoreIncrease();
        }
    
        //if (obstacle.detectCollision(ghost)) {
          //gameState=2;
        //}
      }
    }
    

    Can you help with incorporating the collision detection method below to the work on the ghost class and the obstacles array in my code

      obstacle2 = loadImage("up2.png");
      obstacle1x = (width - obstacle1.width)/2;
      obstacle1y = (height/3 - obstacle1.height)/2;
    //  obstacle2x = (width - obstacle2.width)/4;
    //  obstacle2y = (height - obstacle2.height)/4;
    //    f2x = (width - ghost.width)/2;
    //      f2y = (height - ghost.height)/2;
    }
    
    void draw(){
      background(0);
      image(obstacle1,obstacle1x,obstacle1y);
      obstacle1x = obstacle1x-2;
      if (obstacle1x <= -150){
        obstacle1x = 900;}
      image(ghost,mouseX,mouseY);
      if(pp_collision(obstacle1,obstacle1x,obstacle1y,ghost,mouseX,mouseY)){
        stroke(255,64,64);
        strokeWeight(1);
        noFill();
        rect(obstacle1x,obstacle1y,obstacle1.width,obstacle1.height);
        rect(mouseX,mouseY,ghost.width,ghost.height);
      }
    }
    
    final int ALPHALEVEL = 20;
    
    boolean pp_collision(PImage imgA, float aix, float aiy, PImage imgB, float bix, float biy) {
      int topA, botA, leftA, rightA;
      int topB, botB, leftB, rightB;
      int topO, botO, leftO, rightO;
      int ax, ay;
      int bx, by;
      int APx, APy, ASx, ASy;
      int BPx, BPy; //, BSx, BSy;
    
      topA   = (int) aiy;
      botA   = (int) aiy + imgA.height;
      leftA  = (int) aix;
      rightA = (int) aix + imgA.width;
      topB   = (int) biy;
      botB   = (int) biy + imgB.height;
      leftB  = (int) bix;
      rightB = (int) bix + imgB.width;
    
      if (botA <= topB  || botB <= topA || rightA <= leftB || rightB <= leftA)
        return false;
    
      // If we get here, we know that there is an overlap
      // So we work out where the sides of the overlap are
      leftO = (leftA < leftB) ? leftB : leftA;
      rightO = (rightA > rightB) ? rightB : rightA;
      botO = (botA > botB) ? botB : botA;
      topO = (topA < topB) ? topB : topA;
    
    
      // P is the top-left, S is the bottom-right of the overlap
      APx = leftO-leftA;   
      APy = topO-topA;
      ASx = rightO-leftA;  
      ASy = botO-topA-1;
      BPx = leftO-leftB;   
      BPy = topO-topB;
    
      int widthO = rightO - leftO;
      boolean foundCollision = false;
    
      // Images to test
      imgA.loadPixels();
      imgB.loadPixels();
    
      // These are widths in BYTES. They are used inside the loop
      //  to avoid the need to do the slow multiplications
      int surfaceWidthA = imgA.width;
      int surfaceWidthB = imgB.width;
    
      boolean pixelAtransparent = true;
      boolean pixelBtransparent = true;
    
      // Get start pixel positions
      int pA = (APy * surfaceWidthA) + APx;
      int pB = (BPy * surfaceWidthB) + BPx;
    
      ax = APx; 
      ay = APy;
      bx = BPx; 
      by = BPy;
      for (ay = APy; ay < ASy; ay++) {
        bx = BPx;
        for (ax = APx; ax < ASx; ax++) {
          pixelAtransparent = alpha(imgA.pixels[pA]) < ALPHALEVEL;
          pixelBtransparent = alpha(imgB.pixels[pB]) < ALPHALEVEL;
    
          if (!pixelAtransparent && !pixelBtransparent) {
            foundCollision = true;
            break;
          }
          pA ++;
          pB ++;
          bx++;
        }
        if (foundCollision) break;
        pA = pA + surfaceWidthA - widthO;
        pB = pB + surfaceWidthB - widthO;
        by++;
      }
      return foundCollision;
    }
    
  • Intersection between objects in a array

    So i'm now working on a little game to learn how intersection and atan2 works. And I need some help with the intersection between objects in a array. Why I need your help? Because I don't want the objects overlap eachother. So can you people please help me?

    Heres the draw and setup

    Player p;
    int x = 100;
    int y = 100;
    int grids = 100;
    int enemyCount = 1;
    int bulletCount = 1;
    
    float dEnemy;
    
    boolean wait;
    boolean isLeft, isRight, isUp, isDown;
    
    ArrayList shootBullet = new ArrayList();
    ArrayList enemies = new ArrayList();
    
    void setup() {
      //fullScreen(P3D);
      size(750, 500, P3D);
      p = new Player();
    
      for(int i = 0; i < 2; i++) {
        enemies.add(new enemy());
      }
    }
    
    void draw() {
      background(100);
      stroke(255);
    
      for(int i = 0; i < 41; i++) {
        line(0 + (i * 100), 0, 0 + (i * 100), 4000);
      }
    
      for(int i = 0; i < 41; i++) {
        line(0, 0 + (i * 100), 4000, 0 + (i * 100));
      }
    
    
      if(mousePressed && wait == false) {
        for(int i = 0; i < bulletCount; i++) {
          wait = true;
          shootBullet.add(new shoot());
        }
      } else {
        if(mousePressed == false) {
          wait = false;
        }
      }
    
      for(int i = 0; i < shootBullet.size(); i++) {    
        shoot s = (shoot) shootBullet.get(i);
        s.display();
      }
    
      for(int i = 0; i < enemies.size(); i++) {
        enemy e = (enemy) enemies.get(i);
        e.display();
      }
    
      p.display();
      p.movement();
    }
    
    void keyPressed() {
      setMove(keyCode, true);
    }
    
    void keyReleased() {
      setMove(keyCode, false);
    }
    
    boolean setMove(int k, boolean b) {
      switch (k) {
        case UP:
        return isUp = b;
    
        case DOWN:
        return isDown = b;
    
        case LEFT:
        return isLeft = b;
    
        case RIGHT:
        return isRight = b;
    
        default:
        return b;
      }
    }
    

    Heres my Enemy class (The one that I want to check intersection between the enemies so they stop moving when they hit Eachother)

    class enemy {
      PVector location;
      PVector velocity;
      float a;
      float speed = random(1, 10);
      float r = 50;
      float dPlayer;
    
      enemy() {
        location = new PVector(random(0, 4000), random(0, 4000));
        velocity = new PVector();
      }
    
      void display() {
        a = atan2(p.location.y - location.y, p.location.x - location.x);
        dPlayer = dist(location.x, location.y, p.location.x, p.location.y);
    
        velocity.x = cos(a);
        velocity.y = sin(a);
    
        velocity.x *= speed;
        velocity.y *= speed;
    
        if(dPlayer >= p.r) {
          location.x = location.x + velocity.x;
          location.y = location.y + velocity.y;
        }
    
        ellipse(location.x, location.y, r, r);
      }
    }
    

    Heres my Player class

    class Player {
      PVector location;
      PVector velocity;
      float frict = 0.96;
      int r = 50;
    
      Player() {
        location = new PVector(2000, 2000);
        velocity = new PVector(0, 0);
      }
    
      void display() {
        //pushMatrix();
        colorMode(RGB);
        fill(255);
        camera(location.x, location.y, (height/2.0) / tan(PI*30.0 / 180.0), location.x, location.y, 0, 0, 1, 0); 
        ellipse(location.x, location.y, r, 50r);
        //popMatrix();
      }
    
      void movement() {
        location.x = location.x + velocity.x; 
        location.y = location.y + velocity.y;
        if (isLeft) velocity.x = velocity.x - frict/2;
        if (isRight) velocity.x = velocity.x + frict/2;
        if (isDown) velocity.y = velocity.y + frict/2;
        if (isUp) velocity.y  = velocity.y - frict/2;
        velocity.y = velocity.y * frict;
        velocity.x = velocity.x * frict;
        velocity.x = constrain(velocity.x, -5, 5);
        velocity.y = constrain(velocity.y, -5, 5);
      }
    }
    

    Heres my Shoot class

    class shoot {
      PVector velocity;
      PVector location;
    
      shoot() {
        velocity = new PVector();
        location = new PVector();
        location.x = p.location.x;
        location.y = p.location.y;
        float a = atan2(mouseY - height/2, mouseX - width/2);
        velocity.x = cos(a);
        velocity.y = sin(a);
        velocity.x *= 10;
        velocity.y *= 10;
      }
    
      void display() {
        println(mouseY - height/2);
        println(mouseX - height/2);
        location.x += velocity.x;
        location.y += velocity.y;
        ellipse(location.x, location.y, 10, 10);
      }
    }
    
  • Restarting Game by using keyPressed() not working

    Hi, so I have an assignment where I have to create a game. I have succeeded in creating the game but I am having trouble with restarting the game. I currently have it so when you click the screen the game starts and you use the keys to move the character around the screen and when all of the enemies have been removed the game over screen appears but when I try to press a button to go back to the beginning again it does not work? I have tried adding in a restart() function having looked at other entries on the forum but none of those were using a class so it did not work for me. I really need help as this is due in under a week and I have spent several days trying to figure it out.

    I am using processing version 3.3.5

    The code is shown below:

    PFont font;
    
    int Score;
    //int ScoreIncrease;
    
    Alien oneAlien;
    
    int numberofStars = 300;
    Stars[] theStars = new Stars[numberofStars];
    
    int numberOfEnemies = 2;
    Enemy [] theEnemies = new Enemy[numberOfEnemies];
    int enemySize = 30;
    
    int enemiesRemaining = numberOfEnemies;
    
    boolean GamePlaying = false;
    boolean GameOver = true;
    
    void setup(){
      size(1000,800);
      font = loadFont("Consolas-BoldItalic-48.vlw");
    
      oneAlien = new Alien (150,150, (int) random(width), (int) random(height));
    
      for(int loop = 0; loop<theStars.length; loop++){
        theStars[loop] = new Stars((int) random(width), (int) random(height), 5,5 ,30);
      }
    
      for(int loop = 0; loop<theEnemies.length; loop++){
        theEnemies[loop] = new Enemy((int) random(width), (int) random(height),enemySize);
      }
    
    }//ends setup
    
    void draw(){
      background(0);
      stroke(0);
    
    //draws the stars for the background      
      for (int loop = 0; loop<theStars.length;loop++){
        theStars[loop].drawStars();
      }
      //sets what is to be shown on the screen when the game is not in play
      if(!GamePlaying){
        //print
        textFont(font,48);
        textAlign(CENTER);
        fill(0,250,0);
        text("Click the screen to start", width/2, height/2);
      }
    
      //sets what is shown when the game is in play
      if (GamePlaying) {
       text("Score = " + Score, 800,750);
       text("Time " + millis(), 150,750);
       oneAlien.drawHead();
       oneAlien.drawBody();
       oneAlien.drawEyes();
       oneAlien.drawSpots();
       oneAlien.Bounce();
    
      for(int loop = 0; loop < theEnemies.length; loop++) {
        theEnemies[loop].display();
      }
    
      for(int loop = 0; loop < theEnemies.length; loop++) {
        theEnemies[loop].move();
      }
    
      for(int loop = 0; loop < theEnemies.length; loop++) {
        if(theEnemies[loop].checkForOverlap(oneAlien)) {
          theEnemies[loop].Xloc = -100;
          theEnemies[loop].Yloc = -100;
    
          int timeBonus = int((20000.0 / millis()) * 15);
          Score = Score + 10 +timeBonus;
          enemiesRemaining --;
          if(enemiesRemaining == 0){
            //GameOverScreen();
            GameOver = !GameOver;
          }
          }
        }
       textSize(48);
       fill(255,0,0);
       text("Click screen to pause", width/2, height/16);
    
      }  //ends Game Playing instructions
    
      if (!GameOver){
        background(0);
        textSize(64);
        fill(0,128,0);
        text("You Won!", width/2 ,height/2);
        fill(255);
        text("Press Enter to play again" , width/2, height/2 + 120);
        text("Your score = "+Score, width/2, height/2 +200);
      }//ends Game Over instructions
    
    }//ends draw
    void restart(){
      GameOver = !GameOver;
      GamePlaying = !GamePlaying;
      Score = 0;
      setup();
    
    }//ends restart
    
    
    void mousePressed(){
      //check position
      GamePlaying = !GamePlaying;
    }//ends mouse Pressed
    
    void keyPressed(){
      if (key == CODED) {
        if(keyCode ==UP) {
           oneAlien.moveUp();
        };
        if(keyCode ==DOWN) {
          oneAlien.moveDown();
        };
        if(keyCode ==LEFT) {
          oneAlien.moveLeft();
        };
        if(keyCode ==RIGHT){
         oneAlien.moveRight(); 
        };
        if(keyCode ==ENTER) {
         restart();
         GameOver = !GamePlaying;
        };
    
        }//ends key==coded
    }//ends key pressed
    
    ///////////first class/////////////
    
    class Alien{
    
      //attributes
      int bodyW;
      int bodyH;
      int bodyXloc;
      int bodyYloc;
    
      int headW;
      int headH;
      int headXloc;
      int headYloc;
    
      int spotW;
      int spotH;
      int spotXloc;
      int spotYloc;
    
      int moveBy, moveBy2;
    
      Alien(){
        bodyW = 300;
        bodyH = 400;
        bodyXloc = 450;
        bodyYloc = 450;
    
        moveBy = 1;
        moveBy2 = 1;
      }//end Alien
    
      Alien(int bW, int bH, int xl, int yl){
        bodyW = bW;
        bodyH = bH;
        bodyXloc = xl;
        bodyYloc = yl;
    
        moveBy = 5;
        moveBy2 = 5;
      // do {
       //  moveBy = (int) random(-5,0);
       //  moveBy2 = (int) random(-5,5);
      // }while (moveBy == 0 || moveBy2 == 0);
      }//end
    
      void drawBody(){
        fill(66,149,244);
        rectMode(CENTER);
        rect(bodyXloc, bodyYloc, bodyW, bodyH);
      }//end draw body
    
      void drawHead(){
        fill(244,158,66);
        headW = bodyW / 2;
        headH = bodyH / 2;
        headXloc = bodyXloc;
        headYloc = (bodyYloc - (bodyH / 2) - (headH / 2));
        rect(headXloc, headYloc, headW, headH);
      }//ends draw head
    
      void drawEyes(){
        fill(0);
        rect (headXloc, headYloc, (headW/2), (headH/2));
        float r = random(255);
        float g = random(255);
        float b = random(255);
        fill(r,g,b);
        rect (headXloc, headYloc, (headW/4), (headH/4));    
      }//end eyes
    
      void drawSpots(){
        float r = random(255);
        float g = random(255);
        float b = random(255);
        fill(r,g,b);
        spotW = bodyW / 2;
        spotH = bodyH / 2;
        spotXloc = bodyXloc;
        spotYloc = (bodyYloc - (bodyH / 1500) - (spotH / 1500));
        ellipse(spotXloc, spotYloc, spotW, spotH);     
      }//end draw spots
    
      void Bounce(){
        //checking when hitting right side
        if(bodyXloc >= (width - (bodyW/2))){
          //moveBy = moveBy * -1;
          bodyXloc = (width - (bodyW/2));
        }
    
        //checking when hitting left side
        if(bodyXloc <= (0 +(bodyW / 2))){
         // moveBy = moveBy * -1;
         bodyXloc = (bodyW / 2);
        }
    
        //checking when hitting the top of screen
        if(bodyYloc >= (height - (bodyH/2))){
         // moveBy2 = moveBy2 * -1;
          bodyYloc = (height - (bodyH/2));
        }
        //checking when hitting the bottom of screen
        if(bodyYloc <= (0 +(bodyH / 2 +headH))){
          //moveBy2 = moveBy2 * -1
          bodyYloc = (bodyH / 2 +headH);
        }
      }//ends bounce
    
      void moveUp(){
        bodyYloc = bodyYloc - moveBy2;
      }//end moveUp
    
      void moveDown(){
        bodyYloc = bodyYloc + moveBy2;
      }//ends moveDown
    
      void moveLeft(){
       bodyXloc = bodyXloc - moveBy; 
      }//ends moveLeft
    
      void moveRight(){
        bodyXloc = bodyXloc + moveBy;
      }//ends moveRight
    
      void move(){
        bodyXloc = bodyXloc + moveBy;
        bodyYloc = bodyYloc + moveBy2;
      }//ends move
    
    }//ends class
    
    
    ///////////starts a new class/////////////
    
    class Enemy{
    
      //attributes
      int enemySize;
      int Xloc;
      int Yloc;
      int xSpeed, ySpeed;
    
      Enemy(int Xl, int Yl, int Size) {
        Xloc = Xl;
        Yloc = Yl;
        enemySize = Size;
    
        do{
          xSpeed = (int) random(-10,10);
          ySpeed = (int) random(-10,10);
        }while(xSpeed == 0 || ySpeed == 0);
      }//ends
    
      void display(){
        fill (255,247,0);
        ellipse(Xloc, Yloc, enemySize, enemySize);
      }//ends
    
      void move(){
        Xloc = Xloc + xSpeed;
        Yloc = Yloc + ySpeed;
    
        //checks to make sure that the object will bounce off the top and bottom of the screen
        if (Xloc > width - (enemySize / 2) || Xloc < 0 + (enemySize / 2)){
          xSpeed = xSpeed * -1;
        }
    
        //makes sure that the enemy bounces on the sides of the screen
        if (Yloc > height - (enemySize / 2) || Yloc < 0 + (enemySize / 2)){
          ySpeed = ySpeed * -1;
        }
    
      }//ends
    
      boolean checkForOverlap(Alien oneAlien){
        //System.out.println("Alien x is " +Xloc);
        //System.out.println("Alien y is " +Yloc);    
        //System.out.println("Enemy x is " +oneAlien.bodyXloc);  
        //System.out.println("Enemy y is " +oneAlien.bodyXloc);
    
    
        int alienX = oneAlien.bodyXloc;
        int alienY = oneAlien.bodyYloc;
    
        int distanceApart = (int) dist(Xloc, Yloc, alienX, alienY);
        //System.out.println(distanceApart);
    
        if (distanceApart >(enemySize / 2) + (oneAlien.bodyW / 2) + (oneAlien.headW)){
         // System.out.println("Miss");
          return false;
        }
        else {
         // System.out.println("Crash");
         return true; 
        }
    
      }//end check for overlap
    
    }//ends class
    
    ////////////starts last class/////////////
    
    class Stars{
    
      int starX;
      int starY;
      int starSize;
      int starWidth;
      int starHeight;
    
    
      Stars(){
        starSize = 5;
      }
    
      Stars(int sX, int sY, int sW, int sH, int size){
       starX = sX;
       starY = sY;
       starWidth = sW;
       starHeight = sH;
       starSize = size;
      }
    
      void drawStars(){
        fill(255);
        ellipse(starX, starY, starWidth, starHeight);
      }
    }//end of the class
    
  • How to overlap images with interaction

    I'd like to create a program that has one image on top of the other and then when I move the cursor, the top image is erased to reveal the bottom one. But I'm a total beginner and have no clue where to start. Does anyone have advice on how I could achieve something like this? I've managed to code so that one image loads but I can't figure out how to overlay a second one or to do the interaction bit.

  • Code problem (GUI with 4 buttons)

    Draw the buttons

    They mustn’t overlap

  • Collisions/ End Game

    I got somewhat far with my code, in my eyes, and I have one slight problem. I wanted to make my game end when my white character guy touches any of the fast moving red rectangles. The rectangles were supposed to move side to side, but what I have now will do. I also wanted to collect coins or some sort of rewards, (like pac-man) and then the game will finish. However, since I haven't been able to figure out the whole overlap/distance thing I'm not even sure if that is possible. Does any one have an example to explain this to me, or what I have to add to make this work? I've been trying for a whole week and nothing has worked yet. Thank you.

    PFont title;
    int menu;
    int sub_cnt;
    int sub_cntt;
    int sub_cnttt;
    int earthsize = 30;
    int earth = 200;
    int x=0;
    int y=0;
    float a,b, s=8;
    boolean fireNow = false;
    float xPos = 600;
    float xxPos = 600;
    float xxxPos = 600;
    float xxxxPos = 600;
    int rad = 40;
    int xdirection = 1;
    int ydirection = 1;
    float xspeed = 2.8; 
    float yspeed= 2.2;
    float yPos;
    
    
    
    
    
    
    
    //float rectX;
    //float rectY;
    
    
    
    
    void setup () {
      size(700, 700);
      title = createFont ("font", 28, true);
      menu = 1;
      background(0, 0, 30);
    
    
    }
    
    void draw () {
    
      if (menu == 1) {
        ellipse (random (width), random (height), random (4), random (4));
        textAlign(CENTER);
        textSize(112);
        text ("SEPTUA", 350, 300);
        textSize(30);
        text("press any key to start", 350, 325);
      }
      if (menu == 2) {
        background (0, 0, 30);
        //earth color
        fill(25, 54, 76);
        ellipse(earth, earth + 98,earthsize, earthsize);
        //rectangle (text box)
        fill(0, 0, 60);
        rect (0, 500, 700, 700);
        //text inside the box
        textSize(17);
        fill(255, 255, 255);
        String msg = "IN THE YEAR 3064, EARTH HAS BEEN CONSUMED BY A PLAGUE.";
        text (msg.substring(0,constrain(int(sub_cnt/5),0,msg.length())), 300, 560);
        sub_cnt++;
        if( sub_cnt == 12*msg.length() ){
          menu = 3;
        }
      }
      if ( menu == 3 ) {
        background(0,0,30);
        //earth animation (how it expands)
        fill(25, 54, 76);
        earthsize = earthsize + 1;
        ellipse(earth, earth+98, earthsize, earthsize);
        //text box
        fill(0,0,60);
        rect (0,500,700,700);
        textSize (17);
        fill(255, 255, 255);
        String msg = "THE HUMAN POPULATION HAS DECREASED BY 64%" ;
        text (msg.substring(0, constrain(int(sub_cntt/5), 0,msg.length())), 250, 560);
        sub_cntt++;
        if (sub_cntt == 12*msg.length () ){
          menu= 4;
        }
      }
    
      if (menu ==4) {
    
          background(0);
          text("You're going on a mission to retrieve the cure", width/2, height/2);
          text("Press Z to continue", width/2, height/2-20);
          if(keyPressed==true){
            if (key=='z' || key == 'Z'){
              menu = 6;
            }
          }
          if (keyPressed == true){
          menu= 5;
          }
        }
    
    
    
    
        if (menu ==5){
         ellipse (random (width), random (height), random (4), random (4));
          background (0, 0, 30);
           fill(220,220,220);
          rect(0, 400, 700, 300);
          //this next code is our sprite....
          fill(255, 255, 255);
          rect(x, y, 40, 40);
    
          //this next code will be our enemy
    
          //enemy # 1
          fill(160, 0, 0);
         // xPos = xPos - 1;
          rect(xPos - 20, 200, 40, 40);
          //enemy # 2
          fill(160, 0, 0);
          rect(xxPos - 20, 300, 40, 40);
    
          fill(160, 0, 0);
          rect(xxxPos-20, 400, 40, 40);
    
          fill(160, 0, 0);
          rect(xxxxPos-20, 500, 40, 40);
    
    
    
    
         // xPos = xPos + (xspeed * xdirection);
         // yPos = yPos + (yspeed * ydirection);
         // if(xPos> width-rad|| xPos < rad){
         //  xdirection = -1;
        //  }
    
        //  if (yPos > height-rad || yPos < rad) {
       // ydirection *= -1;
      //}
    
      if (xPos<700){
        xPos= xPos +10;
      }
      else if (xPos-30>600){
        xPos=xPos *-5;
      }
    
       if (xxPos<700){
       xxPos=xxPos +10;
      }
      else if (xPos-40>200){
        xxPos=xxPos *-5;
    
      }
    
           if (xxxPos<700){
      xxxPos=xxxPos+10;
      }
      else if (xxxPos-30>200);
       xxxPos=xxxPos*-5;
    
      }
    
      if (xxxxPos<700){
        xxxxPos=xxxxPos+10;
      }
      else if(xxxxPos-30>200){
        xxxxPos=xxxxPos*-5;
      }
    
    
    
    
    
    
    
    
    
    
    
    
          if (fireNow==true){
            if(a < height && b < width){
              fill(0,191,255);
              rect(a, b, 45, 10);
              a = a+x;
              b = b+(s);
            } else {
              fireNow = false;
    
            }
    
    
          }
        }
    
    
    
    
    void keyPressed() {
      if (menu == 1) {
        menu = 2;
        sub_cnt = 0;
      }
      if (menu == 3) {
        menu = 4;
        sub_cnt = 0;
     }
     if(menu == 4) {
       menu = 5;
       sub_cnt = 0;
     }
    
    
    
    
       if (key == CODED) {
         if (keyCode == UP) {
           y-= 4;
         } else if (keyCode == DOWN) {
           y += 4;
         }
         else if (keyCode ==LEFT) {
           x-= 4;
         }
         else if (keyCode ==RIGHT) {
           x+= 4;
         }
         else if (keyCode == SHIFT) {
           y -= 60;
    }
    }
    
    
        }
    
    
    
    void keyReleased() {
        if (key ==TAB){
          fireNow=true;
          a=x;
          b=y;
        }
      }
    
  • How to change color of overlapping ellipses

    I would like to have the color of the ellipses (or overlaps of the ellipses) change when they have overlapped a few times (let's say 10).

    Do you want to track the ellipses that overlap multiple times so I understand. When two ellipses come together to (almost) full eclipsed state, you will loose information of the overlapping count of each ellipse since you won't be able to distinguish the ellipses from each other after they come apart. More thought is needed in this part.

    Other than that, as mention above, build a class with proper relevant fields. Partial code below.

    Kf

    Class EllipseTrackingObject{
    
    final int RAD=10;
    final color LOW_OVR=color(0,250,0);
    final color MEDIUM_OVR=color(250,150,0);
    final color HIGH_OVR=color(250,0,0);
    
    
      int overlpaCtr;
      color noOverlap;
      color[] overlap;
      float px;
      float py;
    
      //Constructor
      EllipseTrackingObject(){   ...}
    
      void drawEllipse(){  ... }
    
      void checkOverlap(){   ...}
    
      ....etc.
    
    }
    
  • Pattern...

    One approach:

    1. create an array of vector locations for each point in the quad.
    2. interpolate the vectors to animate each list of points. Now you have four independent points tracing paths over the course of 64 frames.
    3. each frame use those four points to draw a quad PShape. (When two points overlap they will naturally form a triangle.)

    For more on how to interpolate a list of vectors, see LerpVectorsExample:

    One thing to notice is that you could define your animation vector data on a unit square -- (0,0), (0,1), (1,1), (1,0). Then you can easily scale the output however you like by multiplying it by the target width and height.

  • Beginner Array Question

    For the first issue:

    You could implement a variable „overlapped“ that initializes to false. If an overlap occurs set the variable to true. Else set it to false.

  • Beginner Array Question

    Sorry to bother you guys again.

    Turning the screen white when two lines overlapped, (line 60 in code above), was just a test. My ultimate goal here was sound related.

    I have a very long sample in the buffer which is mapped to the width of the screen. My desire is that, when any two lines intersect, the sample will trigger from that point in the buffer where they collide ie. if two lines collide in the far left of the screen the sound will trigger somewhere around the beginning of the sample and vice versa.

    Sound triggers fine, but I am having two issues:

    1. When the lines intersect, the sample is triggered continually in accordance with frame rate. I want it to trigger only once per intersection ie. the sound triggers on entry and not continually re-cueing for the duration that two lines overlap.

    2. Despite my best efforts I am unable to get the sample to trigger at the point(s) of contact between the arrays of lines.

    for (int i=0; i<many_Rects.length-1; i++) { for(int j=i+1; j<many_Rects.length; j++) { if (many_Rects[i].overlaps(many_Rects[j])) { println("OVERLAP"); int position = int(map( I_dont_know_What_To_Put_Here, 0, width, 0, groove.length() ) ); groove.cue( position ); } } }

    Could I be a little cheeky and ask for some tips here?

    Thank you!

  • Beginner Array Question
    import ddf.minim.*;
    Minim minim;
    AudioPlayer groove;
    
    int noRects = 3;
    Rect_Class[] many_Rects = new Rect_Class[noRects];
    
    //Rect_Class myRect1;
    //Rect_Class myRect2;
    
    
    int rectW = 320;
    int rectH = 240;
    
    
    
    
    
    void setup()
    {
      frameRate(30);
      //myRect1 = new Rect_Class(int(random(50, 255)), 0.01, random(1, 10));
      //myRect2 = new Rect_Class(int(random(50, 255)), 0.01, random(1, 10));
      for (int i=0; i<many_Rects.length; i++) 
      {
        many_Rects[i] = new Rect_Class(int(random(50, 255)), 0.01, random(1, 10));
      }
      size(displayWidth, displayHeight);
      noStroke();
    
    
      // we pass this to Minim so that it can load files from the data directory
      minim = new Minim(this);
    
      // loadFile will look in all the same places as loadImage does.
      // this means you can find files that are in the data folder and the 
      // sketch folder. you can also pass an absolute path, or a URL.
      groove = minim.loadFile("strings.mp3");
      groove.loop();
    }
    
    
    
    void draw()
    {
      fill(0);
    
      // for(int i=0; i < array1.length-1; i++) {
      //   for(int j=i+1; j < array1.length; j++) {
      //           check array index i against j 
    
    
      for (int i=0; i<many_Rects.length-1; i++) 
      {
        for(int j=i+1; j<many_Rects.length; j++) 
        {
    
          if (many_Rects[i].overlaps(many_Rects[j])) 
          {  
            fill(255);                      // Turn whole screen white
            println("OVERLAP");                 
          } 
        }
      }
    
    
    
      for(int i = 0; i < groove.bufferSize() - 1; i++)
      {
        line(i, 50  + groove.left.get(i)*50,  i+1, 50  + groove.left.get(i+1)*50);
        line(i, 150 + groove.right.get(i)*50, i+1, 150 + groove.right.get(i+1)*50);
      }
    
    
    
    
    
      //draw the background
      rect(0, 0, displayWidth, displayHeight);
    
    
      for (int i=0; i<many_Rects.length; i++) 
      {
        many_Rects[i].calculate();
        many_Rects[i].display();
      }
    }
    
    
    
    class Rect_Class {
      // declare variable accesible within object instance
      int fill;
      float increment;
      float n;
      float xoff;
      float rectWidth = 64;
    
    
    
    
      //initialise
      Rect_Class(int tempFill, float tempIncrement, float tempxOff){
        // pass public variable into local variable
        fill = tempFill;
        increment = tempIncrement;
    
        // initialise all the other local variables
        xoff = tempxOff;
      }
    
    
      void calculate() {
        // locate point along x-axis (via perlin noise caled yo win..
        n = noise(xoff);
        //println("Noise: " + n);
        n *= displayWidth;  // **************** NB ******************
        //println("Scaled Noise: " + n + '\n');
        //with each cycle, increment xoff
        xoff += increment;
      }
    
    
      void display() 
      {
        // Draw the ellipse at the value produced by perlin noise
        fill(fill);
        rect(n, 0, rectWidth, displayHeight);
      }
    
    
      boolean overlaps(Rect_Class other) 
      {
        float d = abs(n - other.n);
        println(d);
        //println(rectWidth + other.rectWidth);
        if (d <= rectWidth) {
          return true;
        } else {
          return false;
        }
      }
    }
    
  • How to make lines of text move back and forth with sine movements?

    I'm basically trying to recreate the way the text moves at 1:42 in this video: youtube.com/watch?v=J-l4-QlV4Cs

    I tried sine functions but everything would overlap, and it was really hard to get color into everything. I'm pretty experienced, but this is a hard one. If anyone can help me or give me some code, thank you.

  • Connect PIR sensor to launch a webcam and a sound

    In 3 appears the screen in black, no image and no sound. Here is the new code:

    import processing.video.*;
    import ddf.minim.*;
    import ddf.minim.AudioPlayer;
    import processing.serial.*;
    
    // Size of each cell in the grid
    int cellSize = 20;
    // Number of columns and rows in our system
    int cols, rows;
    int pirval =0;
    // Variable for capture device
    Capture inputCam01;
    Movie topLayer;
    Minim minim;
    AudioPlayer song;
    Serial myPort;  // Create object from Serial class
    String val;     // Data received from the serial port
    void setup() 
    {
    

    size(1280, 720); frameRate(30); cols = width / cellSize; rows = height / cellSize; colorMode(RGB, 255, 255, 255, 100);

    // This the default video input, see the GettingStartedCapture // example if it creates an error inputCam01 = new Capture(this, width, height);

    // Start capturing the images from the camera inputCam01.start();
    background(0);

    // we pass this to Minim so that it can load files from the data directory minim = new Minim(this);

    // loadFile will look in all the same places as loadImage does. // this means you can find files that are in the data folder and the // sketch folder. you can also pass an absolute path, or a URL. song = minim.loadFile("untitled.wav");

    myPort = new Serial(this, Serial.list()[3], 9600);  // change to your com port number
    }
    
    void movieEvent(Movie topLayer)  
    {  
    topLayer.read();
    }
    
    
    void draw() 
    { 
    
    
    if ( pirval == 1)
    {
    playCamera();
    }
    
    
    if ( pirval == 0)
    {
    song.pause();
    }
    
    thread( "checkSerial");
     }
    
    void playCamera()
    {
    if (inputCam01.available()) {
    song.play();
    
    inputCam01.read();
    inputCam01.loadPixels();
    image(inputCam01, 0, 0);
    
    // Begin loop for columns
    for (int i = 0; i < cols; i++) {
      // Begin loop for rows
      for (int j = 0; j < rows; j++) {
        // Where are we, pixel-wise?
        int x = i*cellSize;
        int y = j*cellSize;
        int loc = (inputCam01.width - x - 1) + y*inputCam01.width; // Reversing x to                                           mirror the image
    
        float r = red(inputCam01.pixels[loc]);
        // Make a new color with an alpha component
        color c = color(r, 50, 50, 75);
    
        // Code for drawing a single rect
        // Using translate in order for rotation to work properly
        pushMatrix();
        translate(x+cellSize/2, y+cellSize/2);
        // Rotation formula based on brightness
        rotate((2 * PI * brightness(c) / 255.0));
        rectMode(CENTER);
        fill(c);
        noStroke();
        // Rects are larger than the cell for some overlap
        rect(0, 0, cellSize+6, cellSize+6);
        popMatrix();
       }
       }
      }
    }
    void checkSerial()
    {
    

    if ( myPort.available() > 0) { // If data is available, val = myPort.readString(); // read it and store it in val if ( trim(val).equals("A") ) { pirval =1; } else { pirval =0; } //print it out in the console println(pirval); } }

  • Connect PIR sensor to launch a webcam and a sound

    No. If you had pressed Ctrl + t like I suggested, you would see why. Look:

    import processing.serial.*;
    import processing.video.*;
    import ddf.minim.*;
    import ddf.minim.AudioPlayer;
    import cc.arduino.*;
    
    // Size of each cell in the grid
    int cellSize = 20;
    // Number of columns and rows in our system
    int cols, rows;
    // Variable for capture device
    Capture inputCam01;
    Movie topLayer;
    Minim minim;
    AudioPlayer song;
    Serial myPort;
    Arduino arduino;
    int ledPin = 13;
    
    
    void setup() {
      size(1280, 720);
      frameRate(30);
      cols = width / cellSize;
      rows = height / cellSize;
      colorMode(RGB, 255, 255, 255, 100);
    
      // This the default video input, see the GettingStartedCapture 
      // example if it creates an error
      inputCam01 = new Capture(this, width, height);
    
      // Start capturing the images from the camera
      inputCam01.start();  
      background(0);
    
      // we pass this to Minim so that it can load files from the data directory
      minim = new Minim(this);
    
      // loadFile will look in all the same places as loadImage does.
      // this means you can find files that are in the data folder and the 
      // sketch folder. you can also pass an absolute path, or a URL.
      song = minim.loadFile("data/untitled.wav");
      song.play();
      song.loop();
    }
    
    
    //// THIS CODE IS NOT IN ANY FUNCTION! THIS CAN'T BE RIGHT.
    {
      // I know that the first port in the serial list on my mac
      // is Serial.list()[0].
      // On Windows machines, this generally opens COM1.
      // Open whatever port is the one you're using.
      String portName = Serial.list()[3]; //change the 0 to a 1 or 2 etc. to match your port
      myPort = new Serial(this, portName, 9600);
    }
    //// ---- TO HERE
    
    
    void movieEvent(Movie topLayer)  
    {  
      topLayer.read();
    }
    
    
    //// THIS CODE IS NOT IN ANY FUNCTION! THIS CAN'T BE RIGHT.
    {
      //println(Arduino.list());
      arduino = new Arduino(this, Arduino.list()[2], 57600);
      arduino.pinMode(ledPin, Arduino.OUTPUT);
    }
    //// ---- TO HERE
    
    void draw() {
      arduino.digitalWrite(ledPin, Arduino.HIGH);
      delay(1000);
      arduino.digitalWrite(ledPin, Arduino.LOW);
      delay(1000);
    } // End of draw()!
    
    
    //// THIS CODE IS NOT IN ANY FUNCTION! THIS CAN'T BE RIGHT.
    { 
      if (inputCam01.available()) {
        inputCam01.read();
        inputCam01.loadPixels();
        image(inputCam01, 0, 0);
    
        // Begin loop for columns
        for (int i = 0; i < cols; i++) {
          // Begin loop for rows
          for (int j = 0; j < rows; j++) {
            // Where are we, pixel-wise?
            int x = i*cellSize;
            int y = j*cellSize;
            int loc = (inputCam01.width - x - 1) + y*inputCam01.width; // Reversing x to mirror       the image
    
            float r = red(inputCam01.pixels[loc]);
            // Make a new color with an alpha component
            color c = color(r, 50, 50, 75);
    
            // Code for drawing a single rect
            // Using translate in order for rotation to work properly
            pushMatrix();
            translate(x+cellSize/2, y+cellSize/2);
            // Rotation formula based on brightness
            rotate((2 * PI * brightness(c) / 255.0));
            rectMode(CENTER);
            fill(c);
            noStroke();
            // Rects are larger than the cell for some overlap
            rect(0, 0, cellSize+6, cellSize+6);
            popMatrix();
          }
        }
      }
    }
    //// ---- TO HERE