使用したUnityのバージョン:2020.3.30f1
地面に付いている間にシフトを押すと飛行し、飛行中にシフトを押すと地面に落ちるようにしています。また飛行中のオブジェクトの高さは10fにしています。
まず地面になるゲームオブジェクトには、groundという名前のタグをつけてください。
次に、飛行させたいゲームオブジェクトに、Rigidbodyをつけて下のコードのスクリプトをアタッチすれば飛行するオブジェクトの完成です。
Rigidbody rb;
bool flying = false;
public float speed = 10f;
void Start()
{
rb = GetComponent<Rigidbody>();
}
void Update()
{
if (Input.GetKey(KeyCode.UpArrow) || Input.GetKey(KeyCode.W)) {
this.transform.position += transform.forward * speed * Time.deltaTime;
}
if (Input.GetKey(KeyCode.DownArrow) || Input.GetKey(KeyCode.S)) {
this.transform.position -= transform.forward * speed * Time.deltaTime;
}
if (Input.GetKey(KeyCode.LeftArrow) || Input.GetKey(KeyCode.A)) {
this.transform.Rotate(0,-1f,0);
}
if (Input.GetKey(KeyCode.RightArrow) || Input.GetKey(KeyCode.D)) {
this.transform.Rotate(0,1f,0);
}
if (Input.GetKeyDown(KeyCode.LeftShift))
{
flight();
}
if (this.transform.position.y > 10f) {
this.transform.position = new Vector3(this.transform.position.x, 10f ,this.transform.position.z);
}
}
void OnCollisionEnter(Collision other)
{
if (other.gameObject.tag == "ground")
{
flying = false;
}
}
void flight()
{
if (flying == false) {
flying = true;
rb.useGravity = false;
rb.AddForce(transform.up * 15f, ForceMode.Impulse);
return;
}
if (flying == true) {
rb.useGravity = true;
return;
}
}
上のコードでは、地面に触れている時にシフトを押すとRigidbodyのUse Gravityのチャックを外し、逆に浮いているときにシフトを押すとUse Gravityのチェックをつけるという方法でオブジェクトを浮かせています。