プレイヤーの移動にはtransformとaddforceが使える。
キー入力でy軸移動するパターンを比較する。
まずはaddForceのスクリプト。
using System.Collections; using System.Collections.Generic; using UnityEngine; public class addforce: MonoBehaviour { // Rigidbodyコンポーネントを入れる変数"rb"を宣言する。 public Rigidbody rb; void Start() { // Rigidbodyコンポーネントを取得する rb = GetComponent<Rigidbody>(); } void FixedUpdate() { // Upキーで前に進む if (Input.GetKey("up")) { rb.AddForce(0, 1f, 0, ForceMode.Impulse); } } }
次がtransformのスクリプト。
using System.Collections; using System.Collections.Generic; using UnityEngine; public class transform : MonoBehaviour { // Start is called before the first frame update void Start() { } // Update is called once per frame void FixedUpdate() { Vector3 pos = this.gameObject.transform.position; if (Input.GetKey("up")) { this.gameObject.transform.position = new Vector3(pos.x, pos.y + 1f, pos.z); } } }
二つの動作の比較をする。
左がaddforce,右がtransform。
addforceのほうは一度力を加えると抵抗がないと吹っ飛んでしまう。
addforceは慣性が働いた動きをしている。transformは決まった量の移動をしている。
タイプに合わせて使い分けるとよさそう。