LoginSignup
2
2

More than 5 years have passed since last update.

ofxBox2d バウンドするカラフルな円

Posted at

ofxBox2dの使い方ソースのメモです。
円をカラフルにしてみました。

box2d.gif

ofApp.h
#pragma once

#include "ofMain.h"
#include "ofxBox2d.h"

class ofApp : public ofBaseApp{

    public:
        void setup();
        void update();
        void draw();

        void keyPressed(int key);
        void keyReleased(int key);
        void mouseMoved(int x, int y );
        void mouseDragged(int x, int y, int button);
        void mousePressed(int x, int y, int button);
        void mouseReleased(int x, int y, int button);
        void windowResized(int w, int h);
        void dragEvent(ofDragInfo dragInfo);
        void gotMessage(ofMessage msg);

        ofxBox2d box2d;

        // 円の数
        static const int CIRCLE_NUM = 30;

        ofxBox2dCircle circle[CIRCLE_NUM];

        // 円の描画色
        ofColor randColor[CIRCLE_NUM];
};

ofApp.cpp
#include "ofApp.h"

//--------------------------------------------------------------
void ofApp::setup(){

    // 背景色を黒に
    ofBackground(0, 0, 0);

    // 円の分割数
    ofSetCircleResolution(64);

    // box2d初期化
    box2d.init();

    // 重力の設定
    box2d.setGravity(0, 0.98);

    // 地面の設定
    box2d.createBounds();

    // フレームレート
    box2d.setFPS(30);

    for(int i = 0; i < CIRCLE_NUM; i++){

        // 質量、跳ね返り係数、摩擦係数
        circle[i].setPhysics(10.0, 1.0, 0.01);

        // 生成する円の中心座標をランダムで設定
        float x = ofRandom(0, ofGetWidth());
        float y = ofRandom(0, ofGetHeight());

        // 円の半径
        float radius = ofRandom(10, 50);

        // 円をBox2dの空間に追加
        circle[i].setup(box2d.getWorld(), x, y, radius);

        // ランダムな色設定
        randColor[i] = ofColor(ofRandom(255), ofRandom(255), ofRandom(255));
    }
}

//--------------------------------------------------------------
void ofApp::update(){

    box2d.update();
}

//--------------------------------------------------------------
void ofApp::draw(){

    for(int i=0; i<CIRCLE_NUM; i++){
        // 円の描画色設定
        ofSetColor(randColor[i]);
        // Box2d空間の円を描画
        circle[i].draw();
    }

}
2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2