我如何使用刚体.用输入移动位置.getaxi是我的方向


void Update()
{
MovementAxes = new Vector2(Input.GetAxis("Horizontal"), Input.GetAxis("Vertical"));
}
void FixedUpdate()
{
HandleMovement(MovementAxes, 60f);
}

void HandleMovement(Vector2 direction, float MovementAmount)
{
if (Input.GetKey("w") || Input.GetKey("s"))
{
if (Input.GetKey("w") && GroundCheck())
{
GetComponent<Rigidbody2D>().MovePosition((Vector2)transform.position + (direction * MovementAmount * Time.fixedDeltaTime));
}
else if (Input.GetKey("s") && !GroundCheck())
{
GetComponent<Rigidbody2D>().MovePosition((Vector2)transform.position + (direction * MovementAmount * Time.fixedDeltaTime));
}
}
}

我有上面的代码,使用Input.GetAxis作为移动动态刚体的两个MovePosition方法的direction参数。

当" "按下键,对象按预期下降,但当按下&;w&;按下键时物体抖动,微微上下移动,但前后不一致。我已经打印出distance,当"w"键时,Input.GetAxis("Vertical")的值为负和正。

如何使用MovePosition来恒定地移动游戏对象。我宁愿使用MovePosition而不是其他Rigidbody方法,因为它据说"创建帧之间的平滑过渡"。(unity)

根据您的问题,我建议将AddForce用于您的Rigidbody2D。下面是一个示例脚本,在Unity中有一个非常简单的2D Movement

public class PlayerController : MonoBehaviour
{
public float speed;
private Rigidbody2D _rigidBody2d;
private void Start()
{
// Cache the value, don't call GetComponent<Rigidbody2D>() in FixedUpdate
_rigidBody2d = GetComponent<Rigidbody2D>();
}
private void FixedUpdate()
{
// Store horizontal and vertical movement
var moveHorizontal = Input.GetAxis("Horizontal");
var moveVertical = Input.GetAxis("Vertical");

// Create the actual movement
var movement = new Vector2(moveHorizontal, moveVertical);
// apply it to your rigidbody by using AddForce
_rigidBody2d.AddForce(movement * speed);
}
}

最新更新