【问题标题】:Correctly move rigidbody at constant speed以恒定速度正确移动刚体
【发布时间】:2021-01-15 02:36:01
【问题描述】:

这是我目前的代码。物体以所需的速度移动,但如果它跳跃则使用 [rb.velocity = movement * speed],它仍然粘在地面上。我无法理解如何解决问题

private Vector3 movement;
private float speed = 3;
public bool isGrounded;

void Start()

rb = GetComponent<Rigidbody>();

void Update()
{
float Horizontal = Input.GetAxis("Horizontal");
float Vertical = Input.GetAxis("Vertical");
movement = transform.right * Horizontal + transform.forward * Vertical;
float origMagnitude = movement.magnitude;
movement.y = 0.0f;
movement = movement.normalized * origMagnitude;

if(isGrounded && Input.GetKeyDown(KeyCode.Space))
rb.AddForce((Vector3.up + movement) * JumpForce, ForceMode.Impulse);

RaycastHit hit;
if (Physics.Raycast(transform.position, transform.TransformDirection(Vector3.down), out hit, rayDistance, layer)) isGrounded = true;
else isGrounded = false;
}

private void FixedUpdate ()
{      
     rb.velocity = movement * speed;
}

【问题讨论】:

    标签: c# unity3d rigid-bodies


    【解决方案1】:

    首先,“AddForce”向刚体添加一个力。这意味着刚体将继续沿这个方向(力矢量)移动,直到有东西阻止它(摩擦或其他物体)。如果不断向刚体施加力,则总力会增加,因此速度会不断增长。

    有一个简单的方法来移动刚体,只需使用它的位置属性:

    例如:

    rb = GetComponent<Rigidbody>(); \\ From your program
    rb.position = rb.position + movement * speed * Time.fixedDeltaTime; \\ Instead of MovePosition
    

    据我所知(来自统一脚本 API)MoveRotation 适用于非运动学刚体。 如果它不起作用,你可以像移动一样做(使用旋转属性)。

    更多信息可以看:Unity Scripting API - Rigidbody

    【讨论】:

    • 谢谢,但是通过这种方式,物体移动但不计算刚体的速度,就好像它是静止的,如果它与某物碰撞它没有影响。我也试过“rb.velocity = 运动 * 速度;”它有效,但这样我在跳跃时遇到问题
    • 你可以设置一次“Addforce”来设置力并停止你可以使用-rigidbody.velocity = Vector3.zero;刚体.angularVelocity = Vector3.zero;这有帮助吗?
    • 不知道我理解的对不对,请问可以写成脚本吗?
    • 例如:if (condition){ rb.addForce (movement * speed);休息状态; } if (到达目的地){ 刚体.速度 = Vector3.zero;刚体.angularVelocity = Vector3.zero; }
    • 我解决了,即使它作为一种方法非常昂贵,但目前我没有其他解决方案。您有什么建议或知道如何沿相机方向旋转吗? private void FixedUpdate () if (movement.sqrMagnitude > 0.0f && isGrounded) if(rb.velocity.sqrMagnitude
    【解决方案2】:

    试着询问速度: 喜欢

    void FixedUpdate()
    { 
        if(rb.velocity.magnitude < "set here your speed variable" )
            rb.velocity = movement * speed;
    }
    

    【讨论】:

    • 通过更改velocity,您将丢弃所有 Unity 引擎物理计算。例如。在坠落过程中,这样的物体不会有任何加速度。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多