当游戏正在运行时,我在关键字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