【问题标题】:Unity3D Configurable Joint component accessing through GetComponentInChildren通过 GetComponentInChildren 访问 Unity3D 可配置关节组件
【发布时间】:2020-04-11 11:35:55
【问题描述】:

我有一个胶囊和一个由可配置关节连接的球体。我使用胶囊刚体移动玩家,球体充当脚轮(就像带悬架的独轮车)。

由于球体是胶囊的子对象,我正在使用 GetComponentInChildren 尝试访问可配置关节、Y 驱动器、位置弹簧(浮点值)。

我在谷歌上搜索这个问题时迷路了。

这里是相关代码,//Comment 中的一切都不起作用:

public class PlayerMovement : MonoBehaviour
{

    private Rigidbody rb;
    public float moveSpeed = 10f;
    public float distanceGround;
    public bool isGrounded = false;
    public bool isCrouch = false;


    void Awake()
    {
        rb = GetComponent<Rigidbody>();
    }

    void Start()
    {
        distanceGround = GetComponent<Collider>().bounds.extents.y;
    }

    void FixedUpdate()
    {
        Movement();
    }

    private void Movement() 
    {
        float inputX = Input.GetAxis("LStickHorz");
        float InputZ = -Input.GetAxis("LStickVert");
        float multiplier = 1f;

        if (!Physics.Raycast (transform.position, -Vector3.up, distanceGround + 1.5f))
        {
            isGrounded = false;
            print("IN AIR.....");
        }
        else
        {
            isGrounded = true;
            print("....onGround");
            //Debug.DrawRay(?,?, Color.red, 1.25f);
        }

        if (Physics.Raycast (transform.position, -Vector3.up, distanceGround + .2f))
        {
            isCrouch = true;
            print("VVVVVVVVVVVVVV");
            //ConfigurableJoint cj = gameObject.GetComponentInChildren(typeof(ConfigurableJoint)) as ConfigurableJoint;
            //set y spring value
            //cj.yDrive.positionSpring = 50f;

        }
        else
        {
            isCrouch = false;
        }

        if (!isGrounded)
        {
            multiplier = .2f;
        }

        if (isCrouch)
        {
            multiplier = .2f;
        }

        Vector3 moveVector = new Vector3(inputX * multiplier, 0.0f, InputZ * multiplier);

        //if ()

        rb.AddForce(moveVector * moveSpeed);
    }
}

【问题讨论】:

    标签: c# unity3d


    【解决方案1】:

    让我们从您的第一条评论开始,函数Debug.DrawRay()。如果您查看文档here,它将告诉您该函数的所有参数并向您展示一个示例。对于这个函数,前两个参数是位置和方向:

    Debug.DrawRay(transform.position, Vector3.up * 5, Color.red, 1.25f)
    

    第二个问题是您不能直接设置positionSpring 字段。您需要将yDrive 的引用存储在另一个变量中,更改positionSpring 的值,然后将yDrive 设置为临时变量:

    // Get the COnfigurableJoint component
    ConfigurableJoint cj = gameObject.GetComponent<ConfigurableJoint>();
    
    // Grab a reference to the JointDrive
    JointDrive jd = cj.yDrive;
    
    // Set the value of positionSpring here
    jd.positionSpring = 50.0f;
    
    // Apply the changes you made to the yDrive back to the ConfigurableJoint
    cj.yDrive = jd;
    

    【讨论】:

    • @RRDAPHNE 没问题。既然这解决了您的问题,您可以点击我的问题的勾号图标吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-02
    相关资源
    最近更新 更多