実際のドローンを想定してゲームパッドを用いるのですが、どうも処理がうまく書けなくて困っております。
内容としては、
一番初めにTakeoffを実行し、ある程度の高さまで上昇したら停止させます。
その後、前進後退、左右、上下の操作を行えるようにしています。
前進後退、左右の操作は右スティック、上下の操作は左スティックで行います。
この際、スティックを倒したら移動し、離したら止まるようにしたいのですが、うまくいかなくて離陸後ずっと止まったままになってしまいます。ソースコードは以下です。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Move : MonoBehaviour {
// Use this for initialization
Rigidbody rigid;
Vector3 start_force,move_force;
bool flag=true;
void Start () {
this.rigid = GetComponent<Rigidbody>();
}
// Update is called once per frame
void Update () {
float h = Input.GetAxisRaw("Horizontal");
float v = Input.GetAxisRaw("Vertical");
float h2 = Input.GetAxisRaw("Horizontal2");
float v2 = Input.GetAxisRaw("Vertical2");
//離陸
if (flag)
{
if (Input.GetButtonDown("Takeoff"))
{
start_force = new Vector3(0.0f, 50.0f, 0.0f);
this.rigid.AddForce(start_force);
Invoke("Stop", 2.0f);
flag = false;
}
}
操作関連が以下です。(上記ソースコードの続きです。)
else if(flag==false) {
//アナログスティック
//左右
if (h2 == 1)
{
move_force = new Vector3(0.0f, 0.0f, 1.0f);
this.rigid.velocity=move_force;
}
if (h2 == -1)
{
move_force = new Vector3(0.0f, 0.0f, -1.0f);
this.rigid.velocity = move_force;
}
//前進後退
if (v2 ==-1)
{
move_force = new Vector3(-1.0f, 0.0f, 1.0f);
this.rigid.velocity = move_force;
}
if (v2==1)
{
move_force = new Vector3(1.0f, 0.0f, 1.0f);
this.rigid.velocity = move_force;
}
//上下
if (v == -1)
{
move_force = new Vector3(0.0f, 1.0f, 0.0f);
this.rigid.velocity = move_force;
}
if (v == 1)
{
move_force = new Vector3(0.0f, -1.0f, 0.0f);
this.rigid.velocity = move_force;
}
//着陸の処理
if (Input.GetButtonDown("Takeoff")){
Debug.Log("land");
Land();
}
}
public void Land()
{
rigid.velocity = Vector3.zero;
Transform droneTransform=this.transform;
Vector3 flight = droneTransform.position;
Vector3 land = new Vector3(flight.x, flight.y, flight.z);
start_force.y = -500.0f;
this.rigid.AddForce(start_force);
}
移動処理はAddforceもしくは、velocityを使用したいと考えています。
最後の着陸は離陸と同じボタンを使用しています。
停止処理に関しては、if文でh2==0のときにStopメソッドを呼び出すなどの処理を書いていたのですが、この処理だと当たり前なことに、開始時点で0なのでStopメソッドでvelocityの値が0になってしまい、これだと移動処理につなげられません。
また、スティックを元に戻したときにピタッと止まるのではなく、そのときのスピードに合わせた停止をさせたいです。(ただ慣性が働いているように見せたい)
良い書き方がないか考えていたのですが、結局思いつかず質問させていただきました。
少し分かりにくいかもしれませんが、ご教授いただけると助かります。