1
1

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 3 years have passed since last update.

Unityで物体を動かす方法

Last updated at Posted at 2021-02-24
1,transform.positionを使う。
//始めの位置を指定する。
this.gameObject.transform.position = new Vector3(0f, 0f, 0f);

またUpdateメソッド内で少しづつ位置を変えることで移動させられる。
:writing_hand::Vector3は構造体(値型)であるので、現在の値を代入したposをもう一度transform.positionに渡す必要がある。

void Update()
{
    //現在の位置を取得
    Vector3 pos = this.gameObject.transform.position;
    //現在の位置からx方向に1移動する
    this.gameObject.transform.position = new Vector3(pos.x + 1, pos.y, pos.z);
}

2.transform.Translateを使う。

void Update()
    {
        // 毎秒その物体のZ軸方向に+1進む
        transform.Translate(Vector3.forward * Time.deltaTime);
        // 毎秒ワールドのX軸方向に+1進む
        transform.Translate(Time.deltaTime, 0f, 0f, Space.World);
    }

3.AddForceを使う
:writing_hand:FixedUpdateは物理量の計算をするときに用いる。
デフォルトでForceMode.Forceとなるので省略できる。

    void FixedUpdate()
    {
        rb.AddForce(0f,2f,0f,ForceMode.Force);
    }
}
ForceMode 詳細
Force 一定に力を加え続ける。質量は考慮される
Acceleration 加速され続ける。 質量は無視される。
Impulse 瞬間に力を加える(爆発のような)質量は考慮される。
VelocityChange 瞬間にその速度になるように力を加える。質量は無視される。

4.MovePositionを使う
MovePositionはRigidbodiがKinematicでも働き滑らかに動く。
Dynamicの時は滑らかよりtransform.position = new posに近くなるので注意

//rb はRigidbodyの型でRigidbodyをGetComponentしている
rb.MovePosition(transform.position + Vector3.forward * Time.deltaTime);

急に移動して衝突判定をすり抜けたくない時に滑らかに動くので役に立つ。

1
1
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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?