一按下W无人机就原地起飞,再按WS就一点用都没有了,改小速度后让它按S有用,但
一按方向键就又失控了。
using System.Collections;
using System.Collections.Generic;
using System.IO.Pipes;
using System.Runtime.CompilerServices;
using System.Security.Cryptography.X509Certificates;
using UnityEngine;
using UnityEngine.UI;
public class Plane_Text : MonoBehaviour
{
private Rigidbody m_Rigidbody;
public float speed = 9;
public float angle = 0;
public float x, y, z;
public Transform target;
void Start()
{
m_Rigidbody = gameObject.GetComponent<Rigidbody>();//获取组件
}
void Update()
{
var vec = new Vector3(x, y, z);
m_Rigidbody.AddForce(vec * speed, ForceMode.Force);//无人机朝vec向量方向运动,至于vec的取值由下面各个按键确定
/无人机飞机控制/
/W加油门(上升);S减油门(下降);A左转;D右转/
if (Input.GetKeyUp(KeyCode.W))
{
speed+=0.5f;
}
if (Input.GetKeyDown(KeyCode.W))
{
x = 0; y = 1f; z = 0;
}
if (Input.GetKeyUp(KeyCode.S))
{
speed -= 0.5f;
}
if (Input.GetKeyDown(KeyCode.D))
{
angle++;
}
this.transform.Rotate(Vector3.up * angle);//按下D键则一直右转,下同
if (Input.GetKeyUp(KeyCode.D))
{
angle = 0;
}
this.transform.Rotate(Vector3.up * angle);//松开D键停止右转,下同
if (Input.GetKeyDown(KeyCode.A))
{
angle--;
}
this.transform.Rotate(Vector3.up * angle);
if (Input.GetKeyUp(KeyCode.A))
{
angle = 0;
}
this.transform.Rotate(Vector3.up * angle);
/↑前倾;↓后倾;←左倾;→右倾/
if (Input.GetKeyDown(KeyCode.LeftArrow))
{
x = -1; y = 1f; z = 0;
}//按下←键朝向量(-1,2,0)方向运动,即左倾,但该左倾只是运动轨迹上左倾,模型是不会往左倾的,所以需要下脚本2里设置
//这个取值随你定,但x一定是负的且z一定是0,至于x和y的大小就看你想飞行轨迹左倾多少来决定了
if (Input.GetKeyUp(KeyCode.LeftArrow))
{
x = 0; y = 1f; z = 0;
}
if (Input.GetKeyDown(KeyCode.RightArrow))
{
x = 1; y = 1f; z = 0;
}
//按下→键
//这些我就不再解释了,跟上面“←键”的是一样的,只是倾斜方向不一样而已
if (Input.GetKeyUp(KeyCode.RightArrow))
{
x = 0; y = 1f; z = 0;
}
if (Input.GetKeyDown(KeyCode.UpArrow))
{
Debug.Log("GetKeyDown(KeyCode.UpArrow)");
x = 0; y = 1f; z = 1f;
}
if (Input.GetKeyUp(KeyCode.UpArrow))
{
x = 0; y = 1f; z = 0;
Debug.Log("GetKeyUp(KeyCode.UpArrow)");
}
if (Input.GetKeyDown(KeyCode.DownArrow))
{
x = 0; y = 1f; z = -1f;
Debug.Log("GetKeyDown(KeyCode.DownArrow)");
}
if (Input.GetKeyUp(KeyCode.DownArrow))
{
x = 0; y = 1f; z = 0;
Debug.Log("GetKeyUp(KeyCode.DownArrow)");
}
}
}
我想让S能控制减速
我给两个修改建议,你可以试试
第一:不要全用if,改为if else if else格式,因为有些按键你是不会同时按的,比如w和s
第二:控制方向和速度改变,都放到KeyDown里边去,比如
if (Input.GetKeyUp(KeyCode.W)) {speed+=0.5f; }
if (Input.GetKeyDown(KeyCode.W)){x = 0; y = 1f; z = 0; }
改为:
if (Input.GetKeyDown(KeyCode.W))
{
speed+=0.5f;
x = 0; y = 1f; z = 0;
}
我试了下你这个代码,减速是没问题的,可能是你的速度太快,又没有设置上下限。
using UnityEngine;
public class Example : MonoBehaviour
{
private Rigidbody m_Rigidbody;
public float speed = 5f;
void Start()
{
m_Rigidbody = GetComponent<Rigidbody>();
}
void Update()
{
float h = Input.GetAxis("Horizontal");
float v = Input.GetAxis("Vertical");
var vec = new Vector3(0f, v, h);
m_Rigidbody.AddForce(vec * speed, ForceMode.Force);
}
}