if (this.a == 1) { this.transform.Translate(Espd, 0, Espd); }
if (this.a == 2) { this.transform.Translate(-Espd, 0, -Espd); }
if (this.a == 3) { this.transform.Translate(-Espd, 0, Espd); }
if (this.a == 4) { this.transform.Translate(Espd, 0, -Espd); }
↑こんな風にtransformで敵を動かしたら壁をすり抜ける現象がたまに起こってしまった。上下左右に移動させる敵はすり抜けないけど斜めに移動させたらすり抜けた。
敵の移動にtransformは使わないほうがいいよとは聞いていたけどやっぱりいろいろ挙動がおかしくなるのね^^;
そこでRigidbodyを付けてaddforceで動かすことにする。
int a = 1; //移動方向を決めるのに使う
float delta = 0; //数を数えるのに使う
float span = 3.0f; //方向転換させるタイマー
float maxSpd = 5; //最高速度
float nowSpd = 0; //今のスピード。最高速度以下なら加速させる
float powX = 25; //X方向に加えるスピード
float powZ = 25; //Z方向に加えるスピード
void FixedUpdate() {
this.delta += Time.deltaTime; //数を数える
if (this.delta > this.span) //スパンまで加算したら
{
this.delta = 0;
this.a = Random.Range(1, 5); //ランダムに方向転換
}
//歩く速度を計測する
this.nowSpd= Mathf.Abs(this.GetComponent<Rigidbody>().velocity.x)+ Mathf.Abs(this.GetComponent<Rigidbody>().velocity.z); //歩く速度を計測。
//壁にハマって動かなくなるのを防止。移動速度が極端に低いということは壁にハマっとる。方向転換させる。
if(this.nowSpd < 1) { this.a = Random.Range(1, 5); }
if (this.a == 1) //左下
{
if (this.nowSpd < maxSpd)
{
this.GetComponent<Rigidbody>().AddForce(transform.right * 1 * powX);
this.GetComponent<Rigidbody>().AddForce(transform.forward * 1 * powZ);
}
}
if (this.a == 2) //右上
{
if (this.nowSpd < maxSpd)
{
this.GetComponent<Rigidbody>().AddForce(transform.right * -1 * powX);
this.GetComponent<Rigidbody>().AddForce(transform.forward * -1 * powZ);
}
}
if (this.a == 3) //左上
{
if (this.nowSpd < maxSpd)
{
this.GetComponent<Rigidbody>().AddForce(transform.right * 1 * powX);
this.GetComponent<Rigidbody>().AddForce(transform.forward * -1 * powZ);
}
}
if (this.a == 4) //右下
{
if (this.nowSpd < maxSpd)
{
this.GetComponent<Rigidbody>().AddForce(transform.right * -1 * powX);
this.GetComponent<Rigidbody>().AddForce(transform.forward * 1 * powZ);
}
}
}
↑このゲームはこちらで公開中↓
ー広告ー