子ノ刻ラボラトリィ

子ノ刻[23:00-01:00]に右脳系ディベロッパが時々お送りするAndroidアプリ開発日誌。主にUnity。最近LINEスタンプ。時々雑記。

キャラクターをタッチ(クリック)したらRagdollが適用されてぐったりする

こんばんは! しんがです。

前回は、モデルにRagdollを適用しました。
Blenderでボーンを入れたモデルにRagdollを適用してみた - 子ノ刻ラボラトリィ

今回はモデルをタッチしたらRagdollを適用されるようにしたいと思います!

Ragdollに置き換える

参考サイト
GP10UnityCourse10 - vga-unity - ミドルウェア (10) - Unity講義まとめページ - Google Project Hosting

実現方法としては、以下の通り。

 ①Ragdollを適用していないモデルのprefabを用意する。
  (ここでは"EnemyPrefab"としました)

 ②Ragdollを適用したモデルのprefabを用意する。
  (ここでは"EnemyRagPrefab"としました)

 ③①のprefabをタッチしたら、②のprefabに置き換える。

なるほどねー
2つ用意しないとだめなのかー

上記のサイトにうまいことやってくれるスクリプトがあったのでC#

using UnityEngine;
using System.Collections;

// 既存のキャラクターをラグドールで置換するためのスクリプト。
public class RagdollGenerator : MonoBehaviour {

	public GameObject ragdollPrefab ; // ラグドールのプレハブ。
	
	// ラグドールの生成。
 	public void Generate(Transform originalRoot , Vector3 velocity) {
		GameObject ragdoll = (GameObject)Instantiate(ragdollPrefab);
		CopyTransformRecursively(originalRoot, ragdoll.transform, velocity);
	}

	// トランスフォームを再帰的にコピーする。
	// ついでに初速の設定も行う。
	private void CopyTransformRecursively(Transform src, Transform dst, Vector3 velocity) {
		dst.localPosition = src.localPosition;
		dst.localRotation = src.localRotation;
		if (dst.rigidbody){
			dst.rigidbody.velocity = velocity;
		}
		foreach (Transform child in src) {
			Transform srcChild = child;
			Transform dstChild = dst.Find(srcChild.name);
			if (dstChild) CopyTransformRecursively(srcChild, dstChild, velocity);
		}
	}
}
RagdollGeneratorの使い方

以前、敵を吹っ飛ばす処理を追加したところを編集。
タッチ(クリック)したGameObjectの取得とキャラクターを吹っ飛ばしてみた - 子ノ刻ラボラトリィ

void Update ()
{
	
	if (TouchManager.selectedGameObject == gameObject) {
		Debug.Log ("Enemy - OnMouseDown");
		float x = Random.Range (-400.0f, 400.0f);
		float y = Random.Range (500.0f, 2000.0f);
		float z = Random.Range (1000.0f, 3000.0f);

		//transform.rigidbody.AddForce (new Vector3 (x, y, z));	
		
		TouchManager.selectedGameObject = null;
	
		//gameObject.GetComponent<RagdollGenerator>().Generate(transform, new Vector3 (x, y, z));
		gameObject.GetComponent<RagdollGenerator>().Generate(transform, new Vector3 (0, 0, 0));

	}
}

これ。
gameObject.GetComponent().Generate(transform, new Vector3 (0, 0, 0));
Vector3 (x, y, z)にしたら一瞬にしてどっかに吹っ飛んでしまったので…


では。

f:id:shinga0221:20130810022146p:plain

クリック!

f:id:shinga0221:20130810023513p:plain

f:id:shinga0221:20130810023517p:plain

おおー!
って、なんか元のprefabも一緒に吹っ飛んでいった(笑)

調査せねば…

修正したUnity Web Playerのサンプル
(修正内容はこちら

でも明日から一週間PCの無い生活に突入です…
前に買った本をしっかり読みこんで、机上でできることを進めたいと思います。

ゲームの作り方  Unityで覚える遊びのアルゴリズム

ゲームの作り方 Unityで覚える遊びのアルゴリズム

買ったのはこの本。


それでは、夜も更けて参りましたので、おやすみなさい。