Created
November 21, 2010 21:47
-
-
Save gintenlabo/709182 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
typedef double real; | |
struct cached_angle | |
{ | |
cached_angle( real x = 0 ) | |
: angle(x), angle_(0), s_(0), c_(1) {} | |
// get angle | |
real& get() { return angle; } | |
real const& get() const { return angle; } | |
// operator real | |
operator real() const { return angle; } | |
// set angle from x, y | |
// returns sqrt( x*x + y*y ) | |
real set_angle_from_xy( real x, real y ) { | |
using std::sqrt; using std::atan2; | |
real const r = sqrt( x*x + y*y ); | |
angle = atan2( y, x ); | |
s = y / r; c = x / r; | |
angle_ = angle; | |
return r; | |
} | |
// update cache ( if updated, returns true ) | |
bool update() const { | |
using std::sin; using std::cos; | |
if( angle_ != angle ) { | |
s_ = sin(angle); | |
c_ = cos(angle); | |
angle_ = angle; | |
return true; | |
} | |
return false; | |
} | |
// get sin-cos pair | |
std::pair<real, real> sincos() const { | |
update(); return std::make_pair( s_, c_ ); | |
} | |
friend std::pair<real, real> sincos( cached_angle const& x ) { | |
return x.sincos(); | |
} | |
real sin() const { | |
update(); return s_; | |
} | |
friend real sin( cached_angle const& x ) { | |
return x.sin(); | |
} | |
real cos() const { | |
update(); return c_; | |
} | |
friend real sin( cached_angle const& x ) { | |
return x.cos(); | |
} | |
private: | |
real angle; | |
mutable real angle_; | |
mutable real s_, c_; | |
}; | |
struct bullet | |
{ | |
real x, y, speed; | |
cached_angle angle; | |
// あと、描画用に幾つかメンバを使う | |
void update() { | |
std::pair<real, real> const sc = angle.sincos(); | |
real const& s = sc.first; real const& c = sc.second; | |
x += c * speed; y += s * speed; | |
if( to_be_deleted() ){ | |
delete(); | |
} | |
draw( x, y, s, c ); // 描画処理に cos と sin を流用 | |
} | |
// dx と dy から speed と angle を設定 | |
void set_vx_vy( real dx, real dy ) { | |
using namespace std; | |
speed = angle.set_angle_from_xy( dx, dy ); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment