坠落时停止物体

时间:2021-02-09 09:08:56

标签: c# unity3d physics

enter image description here

对象有 forwardForce

using UnityEngine;

public class PlayerMovement : MonoBehaviour
{
    public Rigidbody rb; 
    public float forwardForce=800f;
    void Start()
    {
            
    }
    
    void FixedUpdate()
    {
        rb.AddForce(0,0,forwardForce * Time.deltaTime);
        if(Input.GetKey("d")){
            rb.AddForce(30 * Time.deltaTime,0,0, ForceMode.VelocityChange);
        }else if(Input.GetKey("a")){
            rb.AddForce(-30 * Time.deltaTime,0,0, ForceMode.VelocityChange);   
        }
    }
}

现在,问题是我想在坠落时阻止那个物体(不再是在地上)。相机将继续运行,但是,我只想停止那个物体。这意味着如果它不再在地面上,那么 velocity=0

enter image description here

2 个答案:

答案 0 :(得分:0)

我不知道我是否理解你想要什么,
但是如果你想在你的立方体离开地面时停止它,你可以在你的地面下方设置一个触发器,并在它进入触发器时将你的立方体速度设置为 0。

例如:

// A new script you attach to the trigger below the ground
public class DeathTrigger : MonoBehaviour
{
    OnTriggerEnter(Collider other)
    {
        PlayerMovement movement = other.GetComponent<PlayerMovement>();
        if(movement != null)
        {
            // A method you define in your PlayerMovement script 
            // to set your velocity to 0
            movement.ResetVelocity();
        }
    }
}

也许您还想在 rb.useGravity = false; 方法中设置 ResetVelocity() 以防止立方体再次开始倒下。

更新
derHugo 还建议将 rb.velocity = 0;rb.useGravity = false; 替换为 rb.isKinematic = true;,这将阻止刚体使用物理来更新其位置和旋转。

答案 1 :(得分:0)

using UnityEngine;

public class PlayerMovement : MonoBehaviour
{
    public Rigidbody rb; 
    public float forwardForce=1000f;
    

    void FixedUpdate()
    {
        rb.AddForce(0,0,forwardForce * Time.deltaTime);
        if(Input.GetKey("d")){
            rb.AddForce(30 * Time.deltaTime,0,0, ForceMode.VelocityChange);
        }else if(Input.GetKey("a")){
            rb.AddForce(-30 * Time.deltaTime,0,0, ForceMode.VelocityChange);   
        }
        if(Physics.Raycast(transform.position,Vector3.down,0.5f)==false){
            rb.velocity = new Vector3(rb.velocity.x, rb.velocity.y, 0);
        }else{
            
        }
    }
}

我尝试检测播放器是否为 onGrounded。然后,如果玩家未接地,我将速度设置为 0

谢谢Zibelas

相关问题