通過虛擬搖桿控制飛機的左右上下,這次沒有使用控制rotation上的xyz3個軸的值來實現,而是通過每幀增加一個增量來實現
mainRot = this.transform.rotation;.
AddRot.eulerAngles = new Vector3 (pitch, yaw, -roll);
mainRot *= AddRot;
transform.rotation = Quaternion.Lerp (transform.rotation, mainRot, Time.fixedDeltaTime * RotationSpeed);
<span style="white-space:pre"> </span>public void AxisControl (Vector2 axis)
{
if (SimpleControl) {
LimitAxisControl.y = LimitAxisControl.x;
}
roll = Mathf.Lerp (roll, Mathf.Clamp (axis.x, -LimitAxisControl.x, LimitAxisControl.x) * SpeedRoll, Time.deltaTime);
pitch = Mathf.Lerp (pitch, Mathf.Clamp (axis.y, -LimitAxisControl.y, LimitAxisControl.y) * SpeedPitch, Time.deltaTime);
}
<span style="white-space:pre"> </span>public void TurnControl (float turn)
{
yaw += turn * Time.deltaTime * SpeedYaw;
}
flight.AxisControl (new Vector2 (Input.GetAxis ("Mouse X"), Input.GetAxis ("Mouse Y")));
flight.TurnControl(Input.GetAxis("VirtualAxisX"));
flight.TurnControl (Input.GetAxis ("Horizontal"));
如果想要固定某個軸,不讓在這個軸上旋轉,可以以下代碼實現,實現固定某個軸
if (SimpleControl) {
Quaternion saveQ = mainRot; <span style="color:#009900;">//先用saveQ記錄下來這一幀的Quaternion
//再記錄下這一幀的angle</span>
Vector3 fixedAngles = new Vector3 (mainRot.eulerAngles.x, mainRot.eulerAngles.y, mainRot.eulerAngles.z);
if(FixedX) <span style="color:#009900;">//bool值,如果固定X軸,就讓angle對應的值爲1</span>
fixedAngles.x = 1;
if(FixedY)
fixedAngles.y = 1;
if(FixedZ)
fixedAngles.z = 1;
<span style="color:#009900;">//算出固定軸以後的Quaternion,然後讓物體從現在的Quaternion旋轉到固定某個軸以後的Quaternion</span>
saveQ.eulerAngles = fixedAngles;
mainRot = Quaternion.Lerp (mainRot, saveQ, Time.fixedDeltaTime * 2);
}
獲取虛擬按鍵的方法
public void DetectPressedKeyOrButton()
{
foreach (KeyCode kcode in Enum.GetValues(typeof(KeyCode)))
{
if (Input.GetKeyDown(kcode))
{
Debug.Log("KeyCode down: " + kcode);
}
}
}
使用了剛體的子彈,想讓子彈朝目標有偏差的設計,可以用以下方法
Vector3spread = newVector3(Random.Range(-Spread, Spread), Random.Range(-Spread, Spread), Random.Range(-Spread, Spread)) / 100;
Vector3 direction = this.transform.forward + spread;
GameObject bullet = (GameObject)Instantiate(Missile, missileposition, missilerotate);
bullet.transform.forward = direction;