ページ 11

クラス間の値の受け渡し

Posted: 2014年12月12日(金) 21:23
by みぶり
Dxlibを使い、ゲームプログラミングをしているのですが
クラス設計で組んでいるのですが、クラス間での変数の受け渡しの方法がわかりません。

たとえば

クラス プレイヤー{
    int px,py;
}

クラス エネミー{
    int x,y;


クラス プレイヤーと敵との当たり判定{
    ~
}

このように、プレイヤーとエネミーの当たり判定を取りたいときに
エネミークラスのx、y座標の情報

プレイヤーのx、y座標の情報の受け渡しを行うときの方法を教えていただいてもよろしいでしょうか?

Re: クラス間の値の受け渡し

Posted: 2014年12月12日(金) 21:47
by h2so5
一例です。

コード:

#include <cmath>
using namespace std;

struct Position {
	int x, y;	
};

class Object {
public:
	virtual Position Pos() const = 0;
	virtual int Radius() const = 0;
};

class Player : public Object {
public:
	Position Pos() const {
		Position p = {0, 0};
		return p;
	}
	int Radius() const {
		return 5;
	}
};

class Enemy : public Object {
public:
	Position Pos() const {
		Position p = {2, 4};
		return p;
	}
	int Radius() const {
		return 15;
	}
};

class CollisionDetector {
public:
	bool Detect(const Object& obj1, const Object& obj2) {
		double distance = hypot(obj1.Pos().x - obj2.Pos().x, obj1.Pos().y - obj2.Pos().y);
		return (distance < obj1.Radius() + obj2.Radius());
	}
};

int main() {
	CollisionDetector cd;
	Player p;
	Enemy e;
	cd.Detect(p, e);
	return 0;
}

Re: クラス間の値の受け渡し

Posted: 2014年12月14日(日) 14:24
by みぶり
この collisionDetector クラスのDetector関数と return分 は何を意味しているのでしょうか?

Re: クラス間の値の受け渡し

Posted: 2014年12月14日(日) 14:59
by h2so5
2つのオブジェクトが衝突しているかどうかを判定します。