LoginSignup
33
18

More than 3 years have passed since last update.

【Unity】 重力を変更する

Last updated at Posted at 2019-02-15

1.ゲーム全体の重力を変更する方法

ゲーム全体の重力を変更するには、
Edit→Project Settings→Physicsを開いて、

スクリーンショット 2019-02-15 23.30.24.png

InspectorのPhysicsManagerのGravityのVector3の値を変更するだけです!
デフォルトではy軸に-9.81 m/s^2 の力がかかっていますね。地球と同じです。

スクリーンショット 2019-02-15 23.33.59.png

コードから変更する場合は、

Physics.gravity = new Vector3(0,10,0);

こんな感じでできます。

2.特定のオブジェクトのみ重力を変更する方法

特定のオブジェクトに違う重力をかけたい場合は、
以下のコード(ChangeGravity.cs)をオブジェクトにアタッチして、

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ChangeGravity : MonoBehaviour 
{
    [SerializeField] private Vector3 localGravity;
    private Rigidbody rBody;

    // Use this for initialization
    private void Start () 
    {
        rBody = this.GetComponent<Rigidbody>();
        rBody.useGravity = false; //最初にrigidBodyの重力を使わなくする
    }

    private void FixedUpdate () 
    {
        SetLocalGravity (); //重力をAddForceでかけるメソッドを呼ぶ。FixedUpdateが好ましい。
    }

    private void SetLocalGravity()
    {
        rBody.AddForce (localGravity, ForceMode.Acceleration);
    }
}

Inspectorから好きなVector3を入力してあげればOKです。
スクリーンショット 2019-02-15 23.39.14.png

以上、重力を変更する方法でした。

33
18
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
33
18