LoginSignup
16
20

More than 5 years have passed since last update.

[Unity]Rigidbodyの速度を表示する.

Posted at

ボールの速度が欲しい時のスクリプトの書き方の例(Rigidbody)

Ball.cs
using UnityEngine;
using System.Collections;

public class Ball : MonoBehaviour {

    private Rigidbody _rigidbody;

    void Start(){
        // 対象の
        _rigidbody = this.GetComponent<Rigidbody> ();
    }

    void Update(){

        // 1. 速度の取得の例
        // Aキーを推したら
        if (Input.GetKeyDown (KeyCode.A)) {
            // 速度ベクトルを表示
            Debug.Log ("速度ベクトル: " + _rigidbody.velocity);

            // 速度を表示
            Debug.Log ("速度: " + _rigidbody.velocity.magnitude);
        }
    }

    //2. 速度の代入の例
    // 一定速度以上になったら動きを止める

    // 物理的な挙動のため,FixedUpdateを使う.
    void FixedUpdate(){
        // もし速度が5以上だったら
        if (_rigidbody.velocity.magnitude > 5f) {
            // 速度を0にする
            _rigidbody.velocity = Vector3.zero;
            // 重力を無効にする
            _rigidbody.useGravity = false;
            //回転を0にする
            _rigidbody.gameObject.transform.rotation = Quaternion.Euler (Vector3.zero);
        }
    }
}
16
20
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
16
20