We are about to switch to a new forum software. Until then we have removed the registration on this forum.
Rookie question here (so maybe the question is fundamentally wrong.)
If I'm using a library, and I only want a single object from it to be used in a class in my sketch, how should I organize my code?
Let's assume I'm using Kinect libraries, and I have a class that makes use of it. The common approaches are the following ones:
import org.openkinect.processing.*;
Kinect kinect;
Game game;
void setup() {
kinect = new Kinect(this);
game = new Game();
}
class Game {
// code calling methods from the kinect object
}
or
import org.openkinect.processing.*;
Kinect kinect;
Game game;
void setup() {
kinect = new Kinect(this);
game = new Game(kinect);
}
class Game {
Kinect kinect;
Game (Kinect kinect) {
this.kinect = kinect;
}
// code calling methods from the kinect object
}
Is it possible to initialize the object and make the Game class the only one that can see it? I've thought of:
import org.openkinect.processing.*;
Game game;
void setup() {
game = new Game(this);
}
class Game {
Kinect kinect;
Game (PApplet parent) {
kinect = new Kinect(parent);
}
// code calling methods from the kinect object
}
But it looks really weird to me.
Answers
It does look really weird, and it should work, but the difference is that in the first code, you can have many Game objects that all share the same kinect, while in the second code each Game object has its own Kinect object. If you have many Games going at once, each of which use DIFFERENT kinect, then the second approach is more "correct". Maybe you have two instances of your game running at the same time, and two kinects set up for two players to play at once. If you have a single kinect and many Games are all using that one kinect, then the first code is better.
Really it comes down to how many physical Kinects you have. Usually people just have one, which is why the top code looks normal and feels right.
This is the core concept of encapsulation. If you want the Game class to manage your kinect, then kinect should be a member of Game.
Kf