0

現在、次のコードを使用して、オブジェクトを他のゲーム オブジェクトにくっつけています。

void OnCollisionEnter(Collision col)
{
    rb = GetComponent<Rigidbody>();
    rb.isKinematic = true;
    gameObject.transform.SetParent (col.gameObject.transform);
}

それは完全に機能しますが、他の多くの問題を引き起こします。たとえば、衝突後、衝突を検出できなくなります。

誰かがこのコードに代わるものを持っていますか (これにより、ゲームオブジェクトが衝突後に別のオブジェクトにくっつきます)?

4

1 に答える 1

0

ここから始めましょう。これはローテーションを考慮していないことに注意してください。きっと理解できるはずですよね?;)

protected Transform stuckTo = null;
protected Vector3 offset = Vector3.zero;

public void LateUpdate()
{
    if (stuckTo != null)
        transform.position = stuckTo.position - offset;
}

void OnCollisionEnter(Collision col)
{
    rb = GetComponent<Rigidbody>();
    rb.isKinematic = true;

    if(stuckTo == null 
        || stuckTo != col.gameObject.transform)
        offset = col.gameObject.transform.position - transform.position;

    stuckTo = col.gameObject.transform;

}

編集:約束どおり、回転を考慮したより高度なバージョンを次に示します。

Transform stuckTo;
Quaternion offset;
Quaternion look;
float distance;

public void LateUpdate()
{
    if (stuckTo != null)
    {
        Vector3 dir = offset * stuckTo.forward;
        transform.position = stuckTo.position - (dir * distance);
        transform.rotation = stuckTo.rotation * look;
    }
}

void OnCollisionEnter(Collision col)
{
    rb = GetComponent<Rigidbody>();
    rb.isKinematic = true;

    if(stuckTo == null 
        || stuckTo != col.gameObject.transform)
    {
        Vector3 diff = col.gameObject.transform.position - transform.position;
        offset = Quaternion.FromToRotation (col.gameObject.transform.forward, diff.normalized);
        look = Quaternion.FromToRotation (col.gameObject.transform.forward, transform.forward);
        distance = diff.magnitude;
        stuckTo = col.gameObject.transform;
    }
}
于 2015-10-28T18:00:09.283 に答える