|
Unity给角色添加Rigidbody2D的物理推力时,避免角色倾斜
实际上这个问题问的就是如何避免角色旋转角度过大,那解决问题的答案就出来了,可以在update生命周期使用代码限制角色x,y轴的旋转角度(2D角色限制z轴),案例如下(Rigidbody2D案例):
private float PlayerJumpTime=0;
private float PlayerMoveSpeed = 300;
private void Start()
{
PlayerRigidbody = PlayerGameObj.GetComponent<Rigidbody2D>();
}
private void Update()
{
//固定角色平衡
PlayerTF.rotation = new Quaternion(PlayerTF.rotation.x, PlayerTF.rotation.y, 0, 0);
//模块开启停止移动
if (GameManager_Script.TimeSetPanelISOpen==false)
{
//移动角色
//模拟一个向Vector3各种方向的的力,力度为300的运动
if (Input.GetKey(KeyCode.D))
{
PlayerRigidbody.AddForce(Vector3.right * PlayerMoveSpeed);
//print("向右走");
}
if (Input.GetKey(KeyCode.A))
{
PlayerRigidbody.AddForce(Vector3.left * PlayerMoveSpeed);
//print("向左走");
}
if (Input.GetKey(KeyCode.Space))
{
//控制跳跃的时间,不然会跳跃出边界
if (PlayerJumpTime < 0.3f)
{
PlayerJumpTime = PlayerJumpTime + Time.deltaTime;
print(PlayerJumpTime);
PlayerRigidbody.AddForce(Vector3.up * PlayerMoveSpeed);
//print("跳");
}
else
{
PlayerRigidbody.AddForce(Vector3.down * PlayerMoveSpeed);
}
}
else
{
PlayerJumpTime = 0;
PlayerRigidbody.AddForce(Vector3.down * PlayerMoveSpeed);
}
}
}
|