按照Milo Yip大大的思路写了个脚本,在FixedUpdate(Unity文档里写着:, the FixedUpdate function is recommended as the place to apply forces and change Rigidbody settings)计算合力。
public class ForceTest : MonoBehaviour {

    public const float FixedUpdateTimeStep = 0.02f;

    private Vector3 previousVelocity, currentVelocity;

    new Rigidbody rigidbody;
   
    public Vector3 acceleration;

    public Vector3 force;

    public Vector3 addiingForce = new Vector3(0, 1, 0);

    public ForceMode addingForceMode = ForceMode.Impulse;
    void Start () {
        rigidbody = GetComponent<Rigidbody>();
    }
	
	void FixedUpdate () {
      
        previousVelocity = currentVelocity;
        currentVelocity = rigidbody.velocity;
        acceleration = new Vector3((currentVelocity - previousVelocity).x / FixedUpdateTimeStep,
                                   (currentVelocity - previousVelocity).y / FixedUpdateTimeStep,
                                   (currentVelocity - previousVelocity).z / FixedUpdateTimeStep);
        force = acceleration * rigidbody.mass;
        rigidbody.AddForce(addiingForce, addingForceMode);
    }
}

用一个Scale为1的Cube做实验:发现ForceMode为Force或者Acceleration的时候是比较符合牛顿第几定律F=ma的,但是始终有一点误差,记录如图(默认还有-9.8的重力,所以合力应该是0):

Rigibody组件截图:

  1. Force模式:

2.Impulse模式:

3.Velocity Change模式:
4.Acceleration模式:
添加其他方向力的情况:
  1. Force模式:
  2. Acceleration模式:
注意:要是通过力来控制物体,请不要再用Transform来控制物体的位置和移动

阅读更多
个人分类: U
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭
关闭