6
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Unityで曲線を描いてターゲットに進むお話し(n番煎じ)

Last updated at Posted at 2017-03-15

こんにちは。unityで手軽にスクリプトを使って曲線を描いて追尾できないかと考えて実装してみました。僕は15ドルするアセットを持っていたのですが、結局似たようなもんができてしまいました(向こうのほうが確実にリアルだし損はなかった...はず)
#パターン1

sample.cs
  public void HogemoveTowards()
    {  
     Target=GameObject.Find("hogefuga"); //hogegugaに飛んでいくよ
        float speed=1.0f;
        float stepFloat=0;
        stepFloat = Time.deltaTime * speed;
        transform.position = Vector3.MoveTowards(transform.position, Target.transform.position, stepFloat);
    }

Vector3.MoveTowardsを使って実装してみました。動きはなめらかで、スピード調整もある程度スピードの係数を大きくしても遅めの動きなので細かい調整がしやすいです。活用度の高さはこっちのほうがありそうです。
#パターン2

sample2.cs
 public void Hogeslerp()
    {
        Target=GameObject.Find("hogefuga");
     float speed=1.0f;
        var vec = Vector3.Slerp(transform.position, Target.transform.position, Time.deltaTime * speed);
        transform.LookAt(vec);
        transform.position = vec;
    }

こちらはSlerpを使って球形補間型にしてみました。動きの軌道は一緒ですが、係数が小さくても動きが速いです。ホーミング弾を実装するのには最適かもしれません。
#パターン3:クオータニオンで向きを補正する

sample3.cs
public void HogeQuaternion(){
  float Setter=1f;//調整して
  Target=GameObject.Find("hogefuga");
  float stepFloat=0;
  float speed=1;
  stepFloat = Time.deltaTime * 1f;
  transform.position = Vector3.MoveTowards(transform.position, Target.transform.position, stepFloat);  
  transform.rotation = Quaternion.Lerp(transform.rotation, Quaternion.LookRotation(Target.transform.position - transform.position), Time.deltaTime *Setter);
  Vector3 front = transform.TransformDirection(Vector3.forward);
  this.GetComponent<Rigidbody>().AddForce(front*speed,ForceMode.VelocityChange);
}

MoveTowardsと合わせて使うといい感じにターゲットの方を向いて動いてくれます。クオータニオンでターゲットと動くオブジェクトの間を補間できるので便利ですね。Slerpでも動くはずです

#実装例

hoge.cs
using UnityEngine;
using System.Collections;



public class HogeHoge : MonoBehaviour
{
    void Update()
    {
            if (Input.GetMouseButton(1))
            {
                Hoge();
            }
        }
    }
    public void Hoge()
    {
       //パターン1か2か3
    }
}

マウス入力で呼び出せるようにしてみました。私の環境だとこれで無事に動きます。
#注意点など
この実装はただちょっと曲がってターゲットに行くだけです。もっとより自由自在に曲がるポイントを設定したい場合は、ベジェ曲線などを用いて複雑なものを書く必要があります。誰か強い人ベジェ曲線使って追尾システム作ってほしいなぁ(チラッチラッ

6
4
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
6
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?