



public class Vec {
public float _x, _y;
Vec(){
_x = _y = 0;
}
Vec( float x, float y ){
_x = x;
_y = y;
}
//角度を取得する
float getAngle(){
return (float)Math.atan2(_y, _x);
}
//大きさを取得する
float getLength(){
return (float)Math.sqrt( _x*_x + _y*_y );
}
//引数の値より大きさが大きければ引数の値にする
void setLengthCap( float maxLength ){
float len = getLength();
if( maxLength == 0 ){
return; //0割防止
}
if( len > maxLength ){//maxLengthより大きければ大きさをmaxLengthにする
float rate =len/maxLength;
_x /= rate;
_y /= rate;
}
}
// vec方向の向きへrate率ほどブレンドする
void blend( Vec vec, float rate ){
float w = vec._x - _x;
float h = vec._y - _y;
_x += w*rate;
_y += h*rate;
}
}
public class Player extends Task {
private final static float MAX_SPEED = 20; //移動する最大スピード
private final static float SIZE = 20; //自機の大きさ
private Circle _cir = null; //自機の円
private Paint _paint = new Paint(); //描画設定
private Vec _vec = new Vec(); //自機の移動ベクトル
private Vec _sensorVec = new Vec(); //センサーのベクトル
public Player(){
_cir = new Circle( 240, 0, SIZE ); //(240,0)の位置にSIZEの大きさの円を作る
_paint.setColor(Color.BLUE); //色を青に設定
_paint.setAntiAlias(true); //エイリアスをオン
}
// ベクトルをセットする
private void setVec(){
float x = -AcSensor.Inst().getX()*2; //加速度センサーの情報を取得
float y = AcSensor.Inst().getY()*2;
_sensorVec._x = x < 0 ? -x*x : x*x; //2乗して変化を大袈裟にする
_sensorVec._y = y < 0 ? -y*y : y*y; //2乗すると+になるので、負ならマイナスを付ける
_sensorVec.setLengthCap(MAX_SPEED); //ベクトルの大きさが最大スピード以上にならないようにする
_vec.blend( _sensorVec, 0.05f ); //センサーのベクトル方向に実際の移動ベクトルを5%近づける
}
// 移動ベクトルの向いている方に動かす
private void Move(){
_cir._x += _vec._x; //移動ベクトル_vecが指す方向に移動させる
_cir._y += _vec._y;
}
@Override
public boolean onUpdate(){
setVec(); //移動ベクトルをセットする
Move(); //移動ベクトルが向いている方に動かす
return true;
}
@Override
public void onDraw( Canvas c ){
c.drawCircle(_cir._x, _cir._y, _cir._r, _paint);
}
}

Portions of this page are modifications
based on work created and shared by Google and used according to terms
described in the Creative Commons 3.0 Attribution License.
- Remical Soft -