我刚开始一个小项目,我希望玩家从上到下的角度来控制飞船。我希望整个事情都使用基于物理学的运动。
我的问题是,当我向刚体添加力时,它所附着的对象似乎越快地离开其位置。但是,transform.positions似乎还可以。
我把this little unity package放在一起。如果您按下W键,则按下W键的时间越长,船只将越向上并偏离中心。S方向相反。
代码很简单:
using UnityEngine;
using System.Collections;
public class TestController : MonoBehaviour {
public float mainThrust = 100;
private Vector3 cameraOffset = new Vector3(0f, 0f, 150f);
private new Rigidbody rigidbody;
void Start () {
rigidbody = GetComponent<Rigidbody>();
}
void FixedUpdate() {
float axisVertical = Input.GetAxis("Vertical");
Vector2 force = new Vector2(0f, axisVertical) * mainThrust * Time.fixedDeltaTime;
rigidbody.AddRelativeForce(force, ForceMode.Impulse);
Camera.main.transform.position = rigidbody.transform.position - cameraOffset;
Debug.Log("camPos: " + Camera.main.transform.position
+ " - rbPos: " + rigidbody.transform.position);
}
}
任何帮助表示赞赏。
谢谢,
尼科
最佳答案
只需将您的Camera.main.transform.position = rigidbody.transform.position - cameraOffset;
行放在LateUpdate MonoBehaviour方法中,我认为您会很好(如果我正确理解了问题)。如果需要进一步的说明,可以寻找this。
编辑:
这是我用来获取所需结果的脚本(基于您的软件包中找到的脚本):
using UnityEngine;
using System.Collections;
public class TestController : MonoBehaviour
{
public float mainThrust = 100;
private Vector3 cameraOffset = new Vector3(0f, 0f, 150f);
private new Rigidbody rigidbody;
private Vector3 tmpV1 = new Vector3(0f, 0f, 0f);
private Vector3 tmpV2 = new Vector3(0f, 0f, 0f);
// Draw debug cross at camera position
private void drawX()
{
tmpV1.x = Camera.main.transform.position.x - 10f;
tmpV1.y = Camera.main.transform.position.y;
tmpV2.x = Camera.main.transform.position.x + 10f;
tmpV2.y = Camera.main.transform.position.y;
Debug.DrawLine(tmpV1, tmpV2, Color.red);
tmpV1.x = Camera.main.transform.position.x;
tmpV1.y = Camera.main.transform.position.y - 10f;
tmpV2.x = Camera.main.transform.position.x;
tmpV2.y = Camera.main.transform.position.y + 10f;
Debug.DrawLine(tmpV1, tmpV2, Color.red);
}
void Start()
{
rigidbody = GetComponent<Rigidbody>();
}
void FixedUpdate()
{
float axisVertical = Input.GetAxis("Vertical");
// impulse force in Newton
Vector2 force = new Vector2(0f, axisVertical) * mainThrust * Time.fixedDeltaTime;
rigidbody.AddRelativeForce(force, ForceMode.Impulse);
}
void LateUpdate()
{
Camera.main.transform.position = rigidbody.transform.position - cameraOffset;
drawX();
Debug.Log("camPos: " + Camera.main.transform.position + " - rbPos: " + rigidbody.transform.position);
}
}
关于c# - 自上而下的太空飞行物理学-AddForce-物体偏离中心的速度越快,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/40378538/