ofRandom in class constructor problem

Hi all,

Just started with oF/c++ after using Processing for a few years. I am trying to create a random position using a class but it keeps displaying the same thing. I am not sure what to do.

Code in ofApp.h

#pragma once

#include "ofMain.h"

class Particle : public ofBaseApp {
    
    public:
        void setup();
        void update();
        void draw();
    
        Particle();

    float x;
    float y;
    float size;
    
    
};

class ofApp : public ofBaseApp{

	public:
		void setup();
		void update();
		void draw();  
    Particle p;
};

Code in ofApp.cpp:

#include "ofApp.h"

Particle::Particle() {
    x = ofRandom( 0, ofGetWidth() );
    y = ofRandom( 0, ofGetHeight() );
    size = ofRandom(10,200);
}

void Particle::setup() {
    ofSetCircleResolution(100);
}

void Particle::update() {
// empty for now   
}

void Particle::draw() {
    ofSetColor(240,220,20);
    ofCircle(x,y,size);
    
}

//--------------------------------------------------------------
void ofApp::setup(){
    ofSetFrameRate(60);
    ofSetWindowTitle("Particle class");
    ofEnableSmoothing();
    p.setup();

}

//--------------------------------------------------------------
void ofApp::update(){
    p.update();
}

//--------------------------------------------------------------
void ofApp::draw(){
    p.draw();

}

Thanks

which platform are you using?

OSX.

I was following this tutorial:
http://www.openframeworks.cc/tutorials/first%20steps/003_ooops_object_oriented_programming.html

you can make by two options.

# 1. (Pointer)
Particle * p;

p = new Particle();

p->setup();
p->update();
p->draw();

# or 2. (setup() function load)
Particle::Particle() {
}

void Particle::setup() {
    x = ofRandom( 0, ofGetWidth() );
    y = ofRandom( 0, ofGetHeight() );
    size = ofRandom(10,200);
    ofSetCircleResolution(100);
}

Maybe someone explains more better. :slight_smile:

That makes more sense, you are using ofRandom in the Particle setup method.

For some reason it wasn’t working in my constructor, but since it works overall, I’m happy.

Thanks.

using ofGetWidth() / ofGetHeight() in your constructor could be the problem.

your object is member of ofApp so it is constructed during the construction of ofApp and this can happen before oF as a system is setup completely. So the result of ofGetWidth() could be zero.

best practice is to do more complex stuff in the setup ( and don’t call the setup from the constructor :slight_smile: