LoginSignup
0
0

More than 3 years have passed since last update.

Unityでゲームつくりてえ。:自機狙い

Last updated at Posted at 2020-01-01

自機…というか特定の目標を狙って移動させてえ。

自機の方を向かせてまっすぐ移動、という手もある。

こんな感じのを作り、targetに自機を入れる。

public void lookAt(GameObject target,float speed) {
    transform.LookAt(target.transform);
    GetComponent<Rigidbody2D>().velocity = transform.forward.normalized * speed;
}

transformには向きというものがあって?
LookAtを使えば特定のオブジェクトを向かせることができて?
forwardで向きに対しまっすぐに移動させることができる、らしい。

ただこれ、やってみるとわかるが、向きを変えるとオブジェクトの見た目の向きも変わる。
ドットバイドット的なゲームを目指す場合だと、これはきびしい(逆にそこまで気にしないなら、便利なものは使おう)。

さっそく追記(2020/01/01)
http://karaagedigital.hatenablog.jp/entry/2016/09/11/192600
平面が向きを変えてしまうようで、そのままでは2Dではつかえないとのこと。
グラフィックを伴わないオブジェクトなら使いようもあるかもですが、うーむ。

自機の角度を得て、その方向に動かす。

targetに自機を入れると、自分から自機…えーと、「このスクリプトを動作させてる本人」から「目標(自機)」への角度が得られる。

public float target(GameObject target) {
    float x = target.transform.position.x - this.transform.position.x;
    float y = target.transform.position.y - this.transform.position.y;
    float rad = Mathf.Atan2(y,x);
    return rad * Mathf.Rad2Deg;
}

すーがくわからんので、なぜ、という説明はできません。すまん。

こちらは角度を食わせるとその方向に移動するスクリプトになります。
zにさっき得た角度を、objには自分のリジッドボディ2D(Rigidbody2D)を食わせる。

public void moveZ(float z,float speed,Rigidbody2D obj) {
    Vector2 move;
    move.x = Mathf.Cos(Mathf.Deg2Rad * z);
    move.y = Mathf.Sin(Mathf.Deg2Rad * z);
    obj.velocity = move * speed;
}

毎回角度取得と移動を行えば、誘導弾(自機が逃げても追いかける)になる。
初回のみ角度取得し、その角度で移動すると、自機狙い弾(自機にまっすぐ飛ぶ)になる。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0