當遊戲正在運行時,我在關鍵字p上按任意鍵停止,我看到飛船越來越快地移動。但變量推力的價值永遠不會改變。那麼什麼樣的價值顯示和改變使得加速?什麼主意呢?如果我將推力從5改爲10?我如何顯示我的飛船的加速度值?
我添加到我的太空船的一個Rigidbody組件。
我這樣做的方式是正確的方式來加速我的飛船?
我想在OnGUI中顯示每次按下p鍵時加速度的值。
using UnityEngine;
using System.Collections;
public class ControlShip : MonoBehaviour {
public int rotationSpeed = 75;
public int movementspeed = 10;
private int thrust = 5;
Rigidbody _rigidbody;
void Start() {
_rigidbody = GetComponent<Rigidbody>();
Debug.Log("Acc Speed: " + thrust);
}
void Update() {
var v3 = new Vector3(Input.GetAxis("Vertical"), Input.GetAxis("Horizontal"), 0.0f);
transform.Rotate(v3 * rotationSpeed * Time.deltaTime);
transform.position += transform.forward * Time.deltaTime * movementspeed;
if (Input.GetKey(KeyCode.Z))
transform.Rotate(Vector3.forward * rotationSpeed * Time.deltaTime);
if (Input.GetKey("p"))
{
_rigidbody.AddRelativeForce(0f, 0f, thrust, ForceMode.Acceleration);
}
}
void OnGUI()
{
GUI.Label(new Rect(100, 100, 200, 200), "Acc Speed: " + thrust);
}
}
更新
我現在修改後的腳本。當我按下P鍵飛船消失快,加速度的值是0的OnGUI所有的時間:
using UnityEngine;
using System.Collections;
public class ControlShip : MonoBehaviour {
public int rotationSpeed = 75;
public int movementspeed = 10;
private int thrust = 5;
bool isPKeyDown = false;
float acceleration = .0f;
Vector3 previousPosition = Vector3.zero;
Rigidbody _rigidbody;
// Use this for initialization
void Start() {
_rigidbody = GetComponent<Rigidbody>();
Debug.Log("Acc Speed: " + thrust);
}
// Update is called once per frame
void Update() {
var v3 = new Vector3(Input.GetAxis("Vertical"), Input.GetAxis("Horizontal"), 0.0f);
transform.Rotate(v3 * rotationSpeed * Time.deltaTime);
transform.position += transform.forward * Time.deltaTime * movementspeed;
if (Input.GetKey(KeyCode.Z))
transform.Rotate(Vector3.forward * rotationSpeed * Time.deltaTime);
if (Input.GetKey("p"))
{
isPKeyDown = Input.GetKey("p");
float distance = Vector3.Distance(previousPosition, transform.position);
float acceleration = distance/Mathf.Pow(Time.deltaTime, 2);
previousPosition = transform.position;
_rigidbody.AddRelativeForce(0f, 0f, acceleration, ForceMode.Acceleration);
}
}
void OnGUI()
{
if (isPKeyDown)
{
GUI.Label(new Rect(100, 100, 200, 200), "Acc Speed: " + acceleration);
}
}
}
http://answers.unity3d.com/questions/48179/rigidbody-acceleration.html –
你爲什麼想到'thrust'改變,當你從來沒有分配一個新的值它? – TheDjentleman
簡單的童年數學應該告訴你在做什麼(或不做)。 – BugFinder