刚性体2d.movePosition和刚性体2d之间的相互作用如何.添加部队有效?



我正在尝试使用 .AddForce 代码与 .movePosition 代码并列,但 .movePosition 使 .AddForce 什么都不做。我认为是因为这一行:"Vector2 movement = new Vector2 (moveHorizontal, 0(;",但我真的不知道如何解决它。这。AddForce 代码本身按其本身的方式工作。

编辑:发布完整代码。

使用 UnityEngine; 使用系统集合;

public class CompletePlayerController : MonoBehavior {

public float speed;                //Floating point variable to store the player's movement speed.
public float jumpforce;
private Rigidbody2D rb2d;        //Store a reference to the Rigidbody2D component required to use 2D Physics.
// Use this for initialization
void Start()
{
//Get and store a reference to the Rigidbody2D component so that we can access it.
rb2d = GetComponent<Rigidbody2D> ();
}

//FixedUpdate is called at a fixed interval and is independent of frame rate. Put physics code here.
void FixedUpdate()
{
Jump();
//Store the current horizontal input in the float moveHorizontal.
float moveHorizontal = Input.GetAxis ("Horizontal");
//Store the current vertical input in the float moveVertical.
//Use the two store floats to create a new Vector2 variable movement.
Vector2 movement = new Vector2 (moveHorizontal, 0);
//Call the AddForce function of our Rigidbody2D rb2d supplying movement multiplied by speed to move our player.
rb2d.MovePosition ((Vector2)transform.position + (movement * speed * Time.deltaTime));
}
void Jump(){
if (Input.GetButtonDown("Vertical")){
rb2d.AddForce(new Vector2(0, jumpforce), ForceMode2D.Impulse);
}
}

}

顾名思义:

MovePosition

通过计算在下一次物理场更新期间将刚体移动到该位置所需的适当线速度,将刚体移动到指定位置。在移动过程中,重力或线性阻力都不会影响身体。

AddForce

Rigidbody添加力

力在 X 和 Y 方向上指定为两个独立的分量(2D 物理场中没有 Z 方向(。根据定律,物体将被力加速 力 = 质量 x 加速度 - 质量越大,加速到给定速度所需的力就越大。

因此,根据物体的质量和摩擦力,它使物体根据物理学以一定的速度移动。


混合两者没有多大意义,因为MovePosition通常用于isKinematic刚体,因此通过脚本完全控制而AddForce只对isKinematic体有影响,因此仅由物理完全控制;通过混合两者,您不会给AddForce工作的机会,因为您可以使用MovePosition来覆盖Rigodbody的线速度,该将绝对速度调整为刚体从而完全推翻了AddForce.

rb2d.MovePosition (transform.position + (movement * speed * Time.deltaTime));

您希望它移动到的这个目标位置始终与transform.position.y具有相同的Y,因此您基本上将对象钉在该高度。


然而,如果你仔细想想,所有的物理动作都有一个共同点:最后,它们都是在引擎盖下对Rigodbody施加一定速度的不同方式。

因此,与其让这些方法计算速度,不如直接自己更改velocity,从而让AddForce完全控制Y速度,而您只控制X分量:

rb2d.velocity = new Vector2(movement * speed, rb2d.velocity.y);

最新更新