LoginSignup
5
3

More than 5 years have passed since last update.

Unity3D 飛行

Last updated at Posted at 2016-12-30

unityでの飛行をする方法を調べてもあまりしっくりくるものがなかったので、アドバイスを頂きつつも、それっぽいものを作ってみた。
作り方
1.MainCameraをCube内に格納する。CubeにRigidbodyをつける。
2.Edit>ProjectSetting>Inputのところを調整する(後で説明します)
3.ソースコード(C#)をアタッチする。

Inputの設定
kizi.png
重要なのは、このHorizontalとVerticalとPitchで画像のようにする。Yawは演算処理の中に入ってるが、今回はWASDのみで操作することが目標なので、適当にこの四つ以外でキーを割り振ってごまかした(もっといい方法待ってます・・・)

3のソース

Sample.cs
using UnityEngine;
using System.Collections;
using System;

public class PlaneController : MonoBehaviour {
    public float maxPower;
    public float accel;
    public float toruque;
    [SerializeField]
    private float power;
    private Rigidbody body;


    // Use this for initialization
    void Start () {
        body = GetComponent<Rigidbody>();

    }

    // Update is called once per frame
    void Update()
    {

        if (Input.GetKeyDown(KeyCode.Escape)) // 初期位置へスポーン
        {
            transform.position = new Vector3(0, 50f, 0);
            transform.rotation = Quaternion.identity;
            power = 0;
            body.velocity = Vector3.zero;
            body.angularVelocity = Vector3.zero;
        }
        var v = Input.GetAxis("Vertical");
        var h = Input.GetAxis("Horizontal");
        var mouseY = Input.GetAxis("Pitch");
        var mouseX = Input.GetAxis("Yaw");

        // トルクベクトルの計算
        var rotate = (-mouseY * transform.right + mouseX * transform.up + -h * transform.forward).normalized;
        // 与える力の計算(線形補間)
        if (v >= 0) power = Mathf.Lerp(power, maxPower, v * accel * Time.deltaTime);
        else power = Mathf.Lerp(power, 0, -v * accel * Time.deltaTime);

        // 力を与える
        body.AddForce(transform.forward * power);
        body.AddTorque(rotate * toruque);
    }
}

このソースの中でMaxPowerなどがアタッチすると出てきますが、上から100,2,0.5,0にしてみるといいです。
Rigidbodyは各自で空気抵抗を調整してみてください。動きをわかりやすくするためにTerrainで地形を作ってみたほうがいいです。
ではさよなら。

5
3
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
5
3