LoginSignup
1
2

More than 1 year has passed since last update.

剛体(rigidbody)をヒンジで繋いで関節を作り動かす

Posted at

環境

windows11
unity 2020.3.36f1

関節を作ろう

今回関節として繋ぐ三つのオブジェクトを出していきます。ヒエラルキーにカプセルを二つ、スフィアを一つ出します。カプセルを一つArmという名前にして下の図と同じ階層に置きます。
image.png
それぞれのtransformを以下のようにします
image.png
image.png
image.png
以下完成図
image.png
ここまで出来たらCapsule,sphare,Armにリジッドボディを付けます。そしてCapsuleのrigidbodyのis kinematicにチェックを入れ固定します
image.png

ヒンジジョイントを追加して動きを制限しよう

スフィアにヒンジジョイントを追加しconnected bodyにcapsuleを設定し以下のパラメータにします。
image.png
armにもヒンジジョイントを追加しconnected bodyにsphereを設定し以下のパラメータにします。
image.png
スフィアはY軸armはX軸でのみ回転できるようになりました。

コード

以下のコードを書きCapuleにアタッチしましょう。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class arm : MonoBehaviour
{
    GameObject sphere;
    GameObject arm1;
    Rigidbody sphereRb;
    Rigidbody armRb;

    // Start is called before the first frame update
    void Start()
    {
        sphere = GameObject.Find("Sphere");
        sphereRb = sphere.GetComponent<Rigidbody>(); 
        arm1 = GameObject.Find("Arm");
        armRb = arm1.GetComponent<Rigidbody>();
    }

    // Update is called once per frame
    void Update()
    {
        float inputX = Input.GetAxis("Horizontal");
        float inputY = Input.GetAxis("Vertical");
        float angleX = inputX * 60.0f;
        float angleY = inputY * 120.0f;
        armRb.rotation = Quaternion.Euler(angleX, 0.0f, 0.0f);
        sphereRb.rotation = Quaternion.Euler(0.0f, angleY, 0.0f);
    }
}

wasdキーで関節を回転できるようになりました。
関節.gif

1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2