pass a global variable to a class

edited November 2016 in Kinect

I have a particle system over a live video feed with an implementation of OpenCV OpticalFlow.

I need the particles to be affected by opticalflow values - i.e. move left and a right with the person in the video.

I can get the variable aveFlow.x each frame but can't run it through to each particle and change the vector x

full code:

import gab.opencv.*;
import processing.video.*;
import java.awt.*;

//Movie video;
Capture video;
OpenCV opencv;

// DECLARE
ArrayList ballCollection;

float numBalls = 2;

void setup() {
  size(640, 480);
  video = new Capture(this, width/4, height/4);
  opencv = new OpenCV(this, width/4, height/4);
  opencv.loadCascade(OpenCV.CASCADE_FRONTALFACE);  

  //INITIALIZE
  ballCollection = new ArrayList();

  video.start();
}

void draw() {
  //background(0);
  //scale(2);
  opencv.loadImage(video);
  opencv.calculateOpticalFlow();

  image(video, 0, 0, width, height);

  //translate(video.width, 0);
  stroke(255, 0, 0);
  //opencv.drawOpticalFlow();

  PVector aveFlow = opencv.getAverageFlow();
  int flowScale = 100;
  //float optX = aveFlow.x;

  stroke(255);
  strokeWeight(2);
  //line(video.width/2, video.height/2, video.width/2 + aveFlow.x*flowScale, video.height/2 + aveFlow.y*flowScale);
  line(width/2, height/2, width/2 + aveFlow.x*flowScale, height/2 + aveFlow.y*flowScale);

  //numberofballs
  if (ballCollection.size()<numBalls) {
    Ball myBall = new Ball(random(width), 0);
    ballCollection.add(myBall);
  }  

  //CALL FUNCTIONALITY
  for (int i = 0; i < ballCollection.size(); i++) {
    Ball mb = (Ball) ballCollection.get(i);
    mb.run();
  }
}

//void movieEvent(Movie m) {
//  m.read();
//}

void captureEvent(Capture c) {
  c.read();
}

class Ball {

  //global variables
  float x=0;
  float y=0;
  //float speedX = random(-2, 2);
  float speedX = 0;

  float speedY = random(-2, 2);

  //float optY = 0;

  //constructor
  Ball(float _x, float _y) {
    x= _x;
    y= _y;
    //optX = _optX*50;
  }

  //functions
  void run() {
    if (y<height) {
      display();
      move();
      //bounce();
      gravity();
      opticalFlow();
    }
  }

  void opticalFlow() {
    //speedX += aveFlow.x*flowScale;
  }

  void gravity() {
    speedY += 0.01;
  }

  void bounce() {
    if (x > width ) {
      speedX *= -1;
    }
    if (x < 0 ) {
      speedX *= -1;
    }
    if (y > height ) {
      speedY *= -1;
    }
    if (y < 0 ) {
      speedY *= -1;
    }
  }

  void move() {
    x += speedX;
    y += speedY;
  }

  void display() {
    ellipse (x, y, 20, 20);
  }
}

Answers

  • I solved it myself. I was being stupid.

    I need to declare the variable at a global level - outside of setup.

    d'oh.

    not deleted thread so others may learn from my basic mistakes.

  • Thanks for sharing your solution, @digitalmartyn -- I've been there myself, I think most of us have....

Sign In or Register to comment.