Lab 7 in Singapore

Unityでのゲーム開発、プログラミング教育、VR/AR/MR、AI・機械学習に関して。たまにシンガポールのネタも。

2017年05月

【Unity】Transformを使用した移動を試す

前回、Rigidbodyを使用した移動方法を試しました。
http://lab7.blog.jp/archives/2041666.html
今回はTransformを使用した基本的な移動方法を試します。

【次の瞬間の移動先を指定する】
  • position: ワールド空間の位置指定
  • localPosition: 親からの相対的な位置指定 (親がない場合、position と同じ)
  • Translate: 指定した方向と距離に移動

(参照元はUnityマニュアル。
https://docs.unity3d.com/jp/540/ScriptReference/Transform.html

青:position緑:localPosition赤:Translate


このC#ソースは以下です。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MoveTest_2 : MonoBehaviour {
    Vector3 moveDirection;
    void Start () {
       moveDirection = transform.up;
    }
    void FixedUpdate() {
        if (this.name == "Position")
           // positionの設定
           transform.position 
= transform.position + moveDirection * Time.deltaTime;
        else if (this.name == "LocalPosition")
           // localPositionの設定
           transform.localPosition 
= transform.localPosition + moveDirection * Time.deltaTime;
        else if (this.name == "Translate")
           // Translateの設定
           transform.Translate(moveDirection * Time.deltaTime);
    }
}


【Unity】Rigidbodyを使用した移動を試す

Rigidbodyを使用した以下の4つの基本的な移動方法を試しました。

【次の瞬間の移動先を指定する】
  • position: 完全な瞬間移動
  • MovePosition: ほぼ瞬間移動(中間位置を補間できる)
【最初に速度や力を与える】
  • velocity: その瞬間の速度を直接変更
  • AddForce: その瞬間に力を加える
(参考元はUnityマニュアル。

以下のようにY軸方向に一定速度で移動していきます。
青:position緑:MovePosition赤:velocity黄:AddForce


Rigidbody Componentの設定と、このC#ソースは以下です。
Unity_Rigidbody_Test_01
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MoveTest : MonoBehaviour {
    Rigidbody RB;
    Vector3 moveDirection;
    void Start () {
        moveDirection = new Vector3 (0, 1, 0);
        RB = this.GetComponent <Rigidbody> ();
        if (this.name == "Velocity")
            // velocityの設定
            RB.velocity = moveDirection * 1.0f;
        else if (this.name == "AddForce")
            // AddForceの設定
            RB.AddForce(moveDirection * 50.0f);
    }
    void FixedUpdate() {
        if (this.name == "Position")
            // positionの設定
            RB.position = RB.position + moveDirection * 0.02f;
                 else if (this.name == "MovePosition")
            // MovePositionの設定
            RB.MovePosition (RB.position + moveDirection * 0.02f);
    } }



本ブログの内容

本ブログの内容に関して、まずUnityを用いたゲーム開発について
自分の備忘目的の情報や、シェアできる役立つ情報なんかを書いていきます。
徐々にプログラム教育、AIに関する内容まで広げていきたいと思ってます。
シンガポールに長く住んでいるので、そちらのネタもたまに取り上げます。
自己紹介:志知淳一
脱初心者向け Unity基礎本
Game App from Lab7
GooglePlay_Top_2 (Android, iOS) GooglePlay_Top_2 (Android, iOS) GooglePlay_Top_2 (Android, iOS) GooglePlay_Top_2 (Windows) GooglePlay_Top_2 (Android, iOS)
Sponsored Link
Twitter プロフィール
《Unity、プログラミング教育、ARに関して》 Unityの書籍やテキストの執筆、出版。Unityを用いたプログラミング教室。Unityでのゲーム開発、ARアプリ・サービス開発。機械学習/AI。シンガポール12年在住
Lab7 blog in English
Blog Visitors [訪問者数]
  • 累計:

PV [アクセス数]
  • 累計:

Sponsored Link
Contact [お問い合わせ]
Twitter [最近のつぶやき]
Sponsored Link