Help us understand the problem. What is going on with this article?

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

More than 1 year has passed since last update.

既出ですが速度の測り方を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使う方が書く量も少ないし、可読性高いし便利だねっていうお話でした。

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away