【发布时间】:2014-03-25 19:55:10
【问题描述】:
我刚开始学习物理,所以我并不总是确定自己在做什么。这是一个 2D 项目,但我使用的是 SphereCollider 等 3D 物理对象。
我有什么:
物体漂浮在空间中并通过重力相互影响:
protected virtual IEnumerator OnTriggerStay(Collider other) {
yield return new WaitForFixedUpdate();
if(other.attachedRigidbody) {
Vector3 offsetVector = this.transform.position - other.transform.position;
float distance = offsetVector.magnitude;
float gravityForce = (other.rigidbody.mass * mass) / Mathf.Pow(distance, 2);
// Clamp gravity.
if(gravityForce > 1.0F) {
gravityForce = 1.0F;
}
other.attachedRigidbody.constantForce.force = offsetVector.normalized * gravityForce;
}
}
有一些可控制的物体,玩家可以在这些物体上点击并拖动一条线离开物体,以便给它一个相反方向的力(射击)。
我想要达到的目标:
玩家在瞄准时应该能看到大致的预测路线。这意味着路径预测需要考虑当前速度、玩家释放鼠标按钮时施加的力以及周围物体的重力。
到目前为止我所做的尝试:
出于测试目的,我只是将计算/预测的位置保存在一个数组中,然后在 OnDrawGizmos() 中绘制这些位置。
我写了一个方法,它返回某个位置的重力影响,称为 computeGravityForPosition(Vector3 position)。
这就是我尝试计算位置的方式:
private void drawWayPrediction() {
Vector3 pos = this.transform.position;
// The offsetVector for the shooting action.
Vector3 forceVector = pos - Camera.main.ScreenToWorldPoint(Input.mousePosition);
forceVector.z = 0.0F;
// The predicted momentum scaled up to increase the strength.
Vector3 force = (forceVector.normalized * forceVector.magnitude);
// 1. I guess that this is wrong, but don't know how to do it properly.
momentum = this.rigidbody.velocity + force;
for(int i = 0; i < predictionPoints.Length; i++) {
float t = i * Time.fixedDeltaTime;
momentum += computeGravityForPosition(pos);
pos += momentum * t * t;
predictionPoints[i] = pos;
}
}
一开始,当物体慢慢靠近时,看起来还不错。在第一枪之后,预测完全错误。我想这是因为 1. 在代码中。仅仅在速度上增加力可能是可怕的错误。
非常感谢您的宝贵时间。
编辑:
我删除了看似不必要的部分。
我仍然认为主要问题在于 1. 在代码中。我只是不知道如何将物体的当前运动(据我所知统一的物理引擎,我只有当前的速度)与新创建的力混合起来:
Vector3 forceVector = pos - Camera.main.ScreenToWorldPoint(Input.mousePosition); Vector3 force = (forceVector.normalized * forceVector.magnitude);
【问题讨论】:
标签: c# unity3d physics game-physics