Unity FixedJoint

来源:互联网 发布:安装java linux 编辑:程序博客网 时间:2024/06/09 13:36

上次的罗技方向盘项目,开始正式做了。

今天需要给车挂载或卸载农机部分,我觉得应该可以通过设置父子关系或者关节来做。

后来我用了fixedjoint组件,因为有些东西过去真没怎么用过,现在有机会用一下。


先测试了下,得到以下结论

给物体添加Fixed Joint组件,会自动添加上Rigidbody刚体组件,因为依赖关系。
break force:打破关节需要的力, 当固定关节被打破后,fixed joint组件会消失
绑定关节的时候,两个需要绑定的部分如果距离较远,如何移动,是依据质量来的

我做了个demo,当按下按键,两个部分绑定在一起,按另一个键,取消绑定

fixedjoint的绑定是通过设置connectedBody(rigidbody)来进行的,取消绑定似乎不能通过设置connectedBody为null,我试了下好像是报错了,于是取消绑定时我做的是在当前位置生成一个空物体然后将关节绑定在空物体上。

通过代码将两个物体绑定时,默认的是以两个物体当前的位置为准,这通常不会是想要的效果,所以需要 a将utoConfigureConnectedAnchor设为false,然后指定connectedAnchor(vector3,是相对于将要绑定的刚体的坐标)

using System.Collections;using System.Collections.Generic;using UnityEngine;public class PlayerController : MonoBehaviour {    public FixedJoint fj;    float rotateSpeed = 60f;    float speed = 2f;// Use this for initializationvoid Start () {}// Update is called once per framevoid Update () {        float h = Input.GetAxis("Horizontal");        float v = Input.GetAxis("Vertical");        transform.Rotate(transform.up * rotateSpeed * h * Time.deltaTime);        transform.Translate(Vector3.forward * speed * Time.deltaTime*v,Space.Self);        if (Input.GetKeyDown(KeyCode.C)) {            fj.breakForce = Mathf.Infinity;            fj.autoConfigureConnectedAnchor = false;            fj.connectedAnchor = new Vector3(0, 0, 0.5f);            fj.transform.rotation = transform.rotation;            fj.connectedBody = GetComponent<Rigidbody>();        }        if (Input.GetKeyDown(KeyCode.V)) {            GameObject tempObj = new GameObject("tempObj");            Rigidbody rig = tempObj.AddComponent<Rigidbody>();            rig.useGravity = false;            tempObj.transform.position = fj.transform.position;            fj.connectedAnchor = Vector3.zero;            fj.connectedBody = rig;        }    }}