04 playerの往復移動
壁に接触したら反対方向に移動するようにしたい
左右の壁に接触したらflagを制御する
このflagを見てplayerの移動方向を変更したい
左端の壁にtagを設定
tagをWall_Lにする
Player.csを編集
壁との接触判定をする
public class Player : MonoBehaviour{ public bool isWallHit_R;//wall hit flag public bool isWallHit_L;//wall hit flag void Start(){ isWallHit_R = false; //初期化 isWallHit_L = true; //初期化、右に移動したい } //他のオブジェクトとの当たり判定 void OnTriggerEnter( Collider other) { if(other.tag == "Wall_R"){ isWallHit_R = true; isWallHit_L = false; } if(other.tag == "Wall_L"){ isWallHit_R = false; isWallHit_L = true; } } }
Player_Move.csを編集
Player.csの2つのフラグの状況によって、移動を分岐させる
public class Player_Move : MonoBehaviour{ private Player childScript; //Player.csスクリプトを入れる用 public float speed = 3.0f; //移動speed void Start(){ //下の階層のオブジェクトにアタッチしている(Player.cs)を参照 childScript = GetComponentInChildren<Player>(); } void Update(){ //右の壁に接触したら if(childScript.isWallHit_R == true){ //左移動 transform.position -= transform.right * speed * Time.deltaTime; } //左の壁に接触したら if(childScript.isWallHit_L == true){ //右移動 transform.position += transform.right * speed * Time.deltaTime; } } }