简体   繁体   English

刚体在 Unity 中不断移动 (AddForce)

[英]Rigidbody keeps moving in Unity (AddForce)

I want to make my rigidbody sphere move with the "WASD" keys, and so far it works except for a little problem.我想用“WASD”键使我的刚体球体移动,到目前为止,除了一个小问题外,它都可以工作。 When I move the rigidbody, it keeps moving infinitely.当我移动刚体时,它会无限移动。

This is my code:这是我的代码:

rig.AddForce(cam.transform.forward * movementForce * Time.deltaTime, ForceMode.VelocityChange);

Full code: https://pastebin.com/ntjAfDVv完整代码: https://pastebin.com/ntjAfDVv

Well if you don't press any key then you don't stop... You keep moving with whatever the current velocity is.好吧,如果您不按任何键,那么您就不会停止……无论当前速度如何,您都将继续前进。

Also note that for the s key you multiply by movementForce * Time.deltaTime * tempAirMultiplier twice which will most probably result in a significantly lower force then expected!另请注意,对于s键,您乘以movementForce * Time.deltaTime * tempAirMultiplier两次,这很可能会导致显着低于预期的力!

I would probably do something like eg我可能会做类似的事情

    // Tracks if any of the WASD keys is pressed
    var gotInput = false;

    if (Input.GetKey(KeyCode.W))
    {
        rig.AddForce(cam.transform.forward * movementForce * Time.deltaTime * tempAirMultiplier, ForceMode.VelocityChange);
        gotInput = true;
    }
    if (Input.GetKey(KeyCode.A))
    {
        rig.AddForce(cam.transform.right * -movementForce * Time.deltaTime * tempAirMultiplier, ForceMode.VelocityChange);
        gotInput = true;
    }
    if (Input.GetKey(KeyCode.S))
    {
        var force = cam.transform.forward * -movementForce * Time.deltaTime * tempAirMultiplier; // Get relative movement
        // you can simply erase one component like this, no need to create a new Vector3 instance
        force.y = 0; 
        // Note that force already contains your multipliers "Time.deltaTime * movementForce * tempAirMultiplier"
        rig.AddForce(force, ForceMode.VelocityChange);
        gotInput = true;
    }
    if (Input.GetKey(KeyCode.D))
    {
        rig.AddForce(cam.transform.right * tempAirMultiplier, ForceMode.VelocityChange);
        gotInput = true;
    }

    // If none of the keys is pressed stop the rigidbody
    if(!gotInput)
    {
        rig.veolcity = Vector3.zero;
    }

GetKey returns true while the user holds down the key identified by the key KeyCode enum parameter.用户按住由 key KeyCode 枚举参数标识的键时, GetKey返回 true。 Check docs .检查文档 So you might be adding lots of forces.所以你可能会增加很多力量。

Maybe you need to try Input.GetKeyDown that returns true during the frame the user starts pressing down the key identified by name.也许您需要尝试在用户开始按下名称标识的键的帧期间返回 true 的Input.GetKeyDown

I actually could solve the problem by doing this.我实际上可以通过这样做来解决问题。 My answer:我的答案:

rigid.drag = 1;

Inisde the FixedUpdate() function Inisde FixedUpdate() function

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM