LoginSignup
27
29

More than 5 years have passed since last update.

動くObjectの速度の測り方[Unity]

Posted at

既出ですが速度の測り方を2つ紹介します

velocityで測る

超簡単

Rigidbody rigid;
Vector3 speed;

void Start(){
  rigid = GameObject.Find("playerObject").GetComponent<Rigidbody>();
}

void Update(){
  speed = rigid.velocity.magnitude;
}

velocityは速度ベクトル。それのmagnitudeでベクトルの長さ、つまり速度を測れます。
これはRigidbody必須なのでRigidbodyをつけていない物体の速度を測りたい時は次の測り方を利用してください。

フレーム間での移動距離で測る

Vector3 latestPos;
Vector3 speed;
GameObject player;

void Start(){
  player = GameObject.Find("playerObject");
}

void Update(){
  speed 
    = ((player.transform.position - latestPos) / Time.deltaTime).magnitude;
  latestPos = player.transform.position; 
}

playerの座標を毎フレーム最後に取得して、次フレームで移動したplayerの座標と比較してその差分を1フレームの時間Time.deltaTimeで割ると速度を得られます。

感想

やっぱvelocity使う方が書く量も少ないし、可読性高いし便利だねっていうお話でした。

27
29
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
27
29