unity chan

This commit is contained in:
2025-04-30 10:42:18 +07:00
parent 9f2ab79b13
commit c51ba3f899
1170 changed files with 211359 additions and 1 deletions
@@ -0,0 +1,141 @@
//
//AutoBlink.cs
//オート目パチスクリプト
//2014/06/23 N.Kobayashi
//
using UnityEngine;
using System.Collections;
using System.Security;
namespace UnityChan
{
public class AutoBlink : MonoBehaviour
{
public bool isActive = true; //オート目パチ有効
public SkinnedMeshRenderer ref_SMR_EYE_DEF; //EYE_DEFへの参照
public SkinnedMeshRenderer ref_SMR_EL_DEF; //EL_DEFへの参照
public float ratio_Close = 85.0f; //閉じ目ブレンドシェイプ比率
public float ratio_HalfClose = 20.0f; //半閉じ目ブレンドシェイプ比率
[HideInInspector]
public float
ratio_Open = 0.0f;
private bool timerStarted = false; //タイマースタート管理用
private bool isBlink = false; //目パチ管理用
public float timeBlink = 0.4f; //目パチの時間
private float timeRemining = 0.0f; //タイマー残り時間
public float threshold = 0.3f; // ランダム判定の閾値
public float interval = 3.0f; // ランダム判定のインターバル
enum Status
{
Close,
HalfClose,
Open //目パチの状態
}
private Status eyeStatus; //現在の目パチステータス
void Awake ()
{
//ref_SMR_EYE_DEF = GameObject.Find("EYE_DEF").GetComponent<SkinnedMeshRenderer>();
//ref_SMR_EL_DEF = GameObject.Find("EL_DEF").GetComponent<SkinnedMeshRenderer>();
}
// Use this for initialization
void Start ()
{
ResetTimer ();
// ランダム判定用関数をスタートする
StartCoroutine ("RandomChange");
}
//タイマーリセット
void ResetTimer ()
{
timeRemining = timeBlink;
timerStarted = false;
}
// Update is called once per frame
void Update ()
{
if (!timerStarted) {
eyeStatus = Status.Close;
timerStarted = true;
}
if (timerStarted) {
timeRemining -= Time.deltaTime;
if (timeRemining <= 0.0f) {
eyeStatus = Status.Open;
ResetTimer ();
} else if (timeRemining <= timeBlink * 0.3f) {
eyeStatus = Status.HalfClose;
}
}
}
void LateUpdate ()
{
if (isActive) {
if (isBlink) {
switch (eyeStatus) {
case Status.Close:
SetCloseEyes ();
break;
case Status.HalfClose:
SetHalfCloseEyes ();
break;
case Status.Open:
SetOpenEyes ();
isBlink = false;
break;
}
//Debug.Log(eyeStatus);
}
}
}
void SetCloseEyes ()
{
ref_SMR_EYE_DEF.SetBlendShapeWeight (6, ratio_Close);
ref_SMR_EL_DEF.SetBlendShapeWeight (6, ratio_Close);
}
void SetHalfCloseEyes ()
{
ref_SMR_EYE_DEF.SetBlendShapeWeight (6, ratio_HalfClose);
ref_SMR_EL_DEF.SetBlendShapeWeight (6, ratio_HalfClose);
}
void SetOpenEyes ()
{
ref_SMR_EYE_DEF.SetBlendShapeWeight (6, ratio_Open);
ref_SMR_EL_DEF.SetBlendShapeWeight (6, ratio_Open);
}
// ランダム判定用関数
IEnumerator RandomChange ()
{
// 無限ループ開始
while (true) {
//ランダム判定用シード発生
float _seed = Random.Range (0.0f, 1.0f);
if (!isBlink) {
if (_seed > threshold) {
isBlink = true;
}
}
// 次の判定までインターバルを置く
yield return new WaitForSeconds (interval);
}
}
}
}
@@ -0,0 +1,10 @@
fileFormatVersion: 2
guid: 0a6149a22cf8a47a192a60b00b3becb3
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,175 @@
//CameraController.cs for UnityChan
//Original Script is here:
//TAK-EMI / CameraController.cs
//https://gist.github.com/TAK-EMI/d67a13b6f73bed32075d
//https://twitter.com/TAK_EMI
//
//Revised by N.Kobayashi 2014/5/15
//Change : To prevent rotation flips on XY plane, use Quaternion in cameraRotate()
//Change : Add the instrustion window
//Change : Add the operation for Mac
//
using UnityEngine;
using System.Collections;
namespace UnityChan
{
enum MouseButtonDown
{
MBD_LEFT = 0,
MBD_RIGHT,
MBD_MIDDLE,
};
public class CameraController : MonoBehaviour
{
[SerializeField]
private Vector3 focus = Vector3.zero;
[SerializeField]
private GameObject focusObj = null;
public bool showInstWindow = true;
private Vector3 oldPos;
void setupFocusObject(string name)
{
GameObject obj = this.focusObj = new GameObject(name);
obj.transform.position = this.focus;
obj.transform.LookAt(this.transform.position);
return;
}
void Start ()
{
if (this.focusObj == null)
this.setupFocusObject("CameraFocusObject");
Transform trans = this.transform;
transform.parent = this.focusObj.transform;
trans.LookAt(this.focus);
return;
}
void Update ()
{
this.mouseEvent();
return;
}
//Show Instrustion Window
void OnGUI()
{
if(showInstWindow){
GUI.Box(new Rect(Screen.width -210, Screen.height - 100, 200, 90), "Camera Operations");
GUI.Label(new Rect(Screen.width -200, Screen.height - 80, 200, 30),"RMB / Alt+LMB: Tumble");
GUI.Label(new Rect(Screen.width -200, Screen.height - 60, 200, 30),"MMB / Alt+Cmd+LMB: Track");
GUI.Label(new Rect(Screen.width -200, Screen.height - 40, 200, 30),"Wheel / 2 Fingers Swipe: Dolly");
}
}
void mouseEvent()
{
float delta = Input.GetAxis("Mouse ScrollWheel");
if (delta != 0.0f)
this.mouseWheelEvent(delta);
if (Input.GetMouseButtonDown((int)MouseButtonDown.MBD_LEFT) ||
Input.GetMouseButtonDown((int)MouseButtonDown.MBD_MIDDLE) ||
Input.GetMouseButtonDown((int)MouseButtonDown.MBD_RIGHT))
this.oldPos = Input.mousePosition;
this.mouseDragEvent(Input.mousePosition);
return;
}
void mouseDragEvent(Vector3 mousePos)
{
Vector3 diff = mousePos - oldPos;
if(Input.GetMouseButton((int)MouseButtonDown.MBD_LEFT))
{
//Operation for Mac : "Left Alt + Left Command + LMB Drag" is Track
if(Input.GetKey(KeyCode.LeftAlt) && Input.GetKey(KeyCode.LeftCommand))
{
if (diff.magnitude > Vector3.kEpsilon)
this.cameraTranslate(-diff / 100.0f);
}
//Operation for Mac : "Left Alt + LMB Drag" is Tumble
else if (Input.GetKey(KeyCode.LeftAlt))
{
if (diff.magnitude > Vector3.kEpsilon)
this.cameraRotate(new Vector3(diff.y, diff.x, 0.0f));
}
//Only "LMB Drag" is no action.
}
//Track
else if (Input.GetMouseButton((int)MouseButtonDown.MBD_MIDDLE))
{
if (diff.magnitude > Vector3.kEpsilon)
this.cameraTranslate(-diff / 100.0f);
}
//Tumble
else if (Input.GetMouseButton((int)MouseButtonDown.MBD_RIGHT))
{
if (diff.magnitude > Vector3.kEpsilon)
this.cameraRotate(new Vector3(diff.y, diff.x, 0.0f));
}
this.oldPos = mousePos;
return;
}
//Dolly
public void mouseWheelEvent(float delta)
{
Vector3 focusToPosition = this.transform.position - this.focus;
Vector3 post = focusToPosition * (1.0f + delta);
if (post.magnitude > 0.01)
this.transform.position = this.focus + post;
return;
}
void cameraTranslate(Vector3 vec)
{
Transform focusTrans = this.focusObj.transform;
vec.x *= -1;
focusTrans.Translate(Vector3.right * vec.x);
focusTrans.Translate(Vector3.up * vec.y);
this.focus = focusTrans.position;
return;
}
public void cameraRotate(Vector3 eulerAngle)
{
//Use Quaternion to prevent rotation flips on XY plane
Quaternion q = Quaternion.identity;
Transform focusTrans = this.focusObj.transform;
focusTrans.localEulerAngles = focusTrans.localEulerAngles + eulerAngle;
//Change this.transform.LookAt(this.focus) to q.SetLookRotation(this.focus)
q.SetLookRotation (this.focus) ;
return;
}
}
}
@@ -0,0 +1,10 @@
fileFormatVersion: 2
guid: bd026706e81db0440add962177d87b23
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,71 @@
using UnityEngine;
using System.Collections;
namespace UnityChan
{
public class FaceUpdate : MonoBehaviour
{
public AnimationClip[] animations;
Animator anim;
public float delayWeight;
public bool isKeepFace = false;
void Start ()
{
anim = GetComponent<Animator> ();
}
void OnGUI ()
{
GUILayout.Box ("Face Update", GUILayout.Width (170), GUILayout.Height (25 * (animations.Length + 2)));
Rect screenRect = new Rect (10, 25, 150, 25 * (animations.Length + 1));
GUILayout.BeginArea (screenRect);
foreach (var animation in animations) {
if (GUILayout.RepeatButton (animation.name)) {
anim.CrossFade (animation.name, 0);
}
}
isKeepFace = GUILayout.Toggle (isKeepFace, " Keep Face");
GUILayout.EndArea ();
}
float current = 0;
void Update ()
{
if (Input.GetMouseButton (0)) {
current = 1;
} else if (!isKeepFace) {
current = Mathf.Lerp (current, 0, delayWeight);
}
anim.SetLayerWeight (1, current);
}
//アニメーションEvents側につける表情切り替え用イベントコール
public void OnCallChangeFace (string str)
{
int ichecked = 0;
foreach (var animation in animations) {
if (str == animation.name) {
ChangeFace (str);
break;
} else if (ichecked <= animations.Length) {
ichecked++;
} else {
//str指定が間違っている時にはデフォルトで
str = "default@unitychan";
ChangeFace (str);
}
}
}
void ChangeFace (string str)
{
isKeepFace = true;
current = 1;
anim.CrossFade (str, 0);
}
}
}
@@ -0,0 +1,10 @@
fileFormatVersion: 2
guid: 5e658bfc1e524494b9e54a1c92d8c1e0
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,53 @@
//
//IKCtrlRightHand.cs
//
//Sample script for IK Control of Unity-Chan's right hand.
//
//2014/06/20 N.Kobayashi
//
using UnityEngine;
using System.Collections;
namespace UnityChan
{
[RequireComponent(typeof(Animator))]
public class IKCtrlRightHand : MonoBehaviour
{
private Animator anim;
public Transform targetObj = null;
public bool isIkActive = false;
public float mixWeight = 1.0f;
void Awake ()
{
anim = GetComponent<Animator> ();
}
void Update ()
{
//Kobayashi
if (mixWeight >= 1.0f)
mixWeight = 1.0f;
else if (mixWeight <= 0.0f)
mixWeight = 0.0f;
}
void OnAnimatorIK (int layerIndex)
{
if (isIkActive) {
anim.SetIKPositionWeight (AvatarIKGoal.RightHand, mixWeight);
anim.SetIKRotationWeight (AvatarIKGoal.RightHand, mixWeight);
anim.SetIKPosition (AvatarIKGoal.RightHand, targetObj.position);
anim.SetIKRotation (AvatarIKGoal.RightHand, targetObj.rotation);
}
}
void OnGUI ()
{
Rect rect1 = new Rect (10, Screen.height - 20, 400, 30);
isIkActive = GUI.Toggle (rect1, isIkActive, "IK Active");
}
}
}
@@ -0,0 +1,10 @@
fileFormatVersion: 2
guid: 16931e3bbabb00f478bbbe4759af8343
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,108 @@
using UnityEngine;
using System.Collections;
namespace UnityChan
{
//
// ↑↓キーでループアニメーションを切り替えるスクリプト(ランダム切り替え付き)Ver.3
// 2014/04/03 N.Kobayashi
//
// Require these components when using this script
[RequireComponent(typeof(Animator))]
public class IdleChanger : MonoBehaviour
{
private Animator anim; // Animatorへの参照
private AnimatorStateInfo currentState; // 現在のステート状態を保存する参照
private AnimatorStateInfo previousState; // ひとつ前のステート状態を保存する参照
public bool _random = false; // ランダム判定スタートスイッチ
public float _threshold = 0.5f; // ランダム判定の閾値
public float _interval = 10f; // ランダム判定のインターバル
//private float _seed = 0.0f; // ランダム判定用シード
// Use this for initialization
void Start ()
{
// 各参照の初期化
anim = GetComponent<Animator> ();
currentState = anim.GetCurrentAnimatorStateInfo (0);
previousState = currentState;
// ランダム判定用関数をスタートする
StartCoroutine ("RandomChange");
}
// Update is called once per frame
void Update ()
{
// ↑キー/スペースが押されたら、ステートを次に送る処理
if (Input.GetKeyDown ("up") || Input.GetButton ("Jump")) {
// ブーリアンNextをtrueにする
anim.SetBool ("Next", true);
}
// ↓キーが押されたら、ステートを前に戻す処理
if (Input.GetKeyDown ("down")) {
// ブーリアンBackをtrueにする
anim.SetBool ("Back", true);
}
// "Next"フラグがtrueの時の処理
if (anim.GetBool ("Next")) {
// 現在のステートをチェックし、ステート名が違っていたらブーリアンをfalseに戻す
currentState = anim.GetCurrentAnimatorStateInfo (0);
if (previousState.nameHash != currentState.nameHash) {
anim.SetBool ("Next", false);
previousState = currentState;
}
}
// "Back"フラグがtrueの時の処理
if (anim.GetBool ("Back")) {
// 現在のステートをチェックし、ステート名が違っていたらブーリアンをfalseに戻す
currentState = anim.GetCurrentAnimatorStateInfo (0);
if (previousState.nameHash != currentState.nameHash) {
anim.SetBool ("Back", false);
previousState = currentState;
}
}
}
void OnGUI ()
{
GUI.Box (new Rect (Screen.width - 110, 10, 100, 90), "Change Motion");
if (GUI.Button (new Rect (Screen.width - 100, 40, 80, 20), "Next"))
anim.SetBool ("Next", true);
if (GUI.Button (new Rect (Screen.width - 100, 70, 80, 20), "Back"))
anim.SetBool ("Back", true);
}
// ランダム判定用関数
IEnumerator RandomChange ()
{
// 無限ループ開始
while (true) {
//ランダム判定スイッチオンの場合
if (_random) {
// ランダムシードを取り出し、その大きさによってフラグ設定をする
float _seed = Random.Range (0.0f, 1.0f);
if (_seed < _threshold) {
anim.SetBool ("Back", true);
} else if (_seed >= _threshold) {
anim.SetBool ("Next", true);
}
}
// 次の判定までインターバルを置く
yield return new WaitForSeconds (_interval);
}
}
}
}
@@ -0,0 +1,10 @@
fileFormatVersion: 2
guid: 058a2736f2afd564eae55007a87eed87
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,45 @@
//
//RandomWind.cs for unity-chan!
//
//Original Script is here:
//ricopin / RandomWind.cs
//Rocket Jump : http://rocketjump.skr.jp/unity3d/109/
//https://twitter.com/ricopin416
//
using UnityEngine;
using System.Collections;
namespace UnityChan
{
public class RandomWind : MonoBehaviour
{
private SpringBone[] springBones;
public bool isWindActive = true;
// Use this for initialization
void Start ()
{
springBones = GetComponent<SpringManager> ().springBones;
}
// Update is called once per frame
void Update ()
{
Vector3 force = Vector3.zero;
if (isWindActive) {
force = new Vector3 (Mathf.PerlinNoise (Time.time, 0.0f) * 0.005f, 0, 0);
}
for (int i = 0; i < springBones.Length; i++) {
springBones [i].springForce = force;
}
}
void OnGUI ()
{
Rect rect1 = new Rect (10, Screen.height - 40, 400, 30);
isWindActive = GUI.Toggle (rect1, isWindActive, "Random Wind");
}
}
}
@@ -0,0 +1,10 @@
fileFormatVersion: 2
guid: a38e39ada51aaba4db6d352ce218849e
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,135 @@
//
//SpringBone.cs for unity-chan!
//
//Original Script is here:
//ricopin / SpringBone.cs
//Rocket Jump : http://rocketjump.skr.jp/unity3d/109/
//https://twitter.com/ricopin416
//
//Revised by N.Kobayashi 2014/06/20
//
using UnityEngine;
using System.Collections;
namespace UnityChan
{
public class SpringBone : MonoBehaviour
{
//次のボーン
public Transform child;
//ボーンの向き
public Vector3 boneAxis = new Vector3 (-1.0f, 0.0f, 0.0f);
public float radius = 0.05f;
//各SpringBoneに設定されているstiffnessForceとdragForceを使用するか?
public bool isUseEachBoneForceSettings = false;
//バネが戻る力
public float stiffnessForce = 0.01f;
//力の減衰力
public float dragForce = 0.4f;
public Vector3 springForce = new Vector3 (0.0f, -0.0001f, 0.0f);
public SpringCollider[] colliders;
public bool debug = true;
//Kobayashi:Thredshold Starting to activate activeRatio
public float threshold = 0.01f;
private float springLength;
private Quaternion localRotation;
private Transform trs;
private Vector3 currTipPos;
private Vector3 prevTipPos;
//Kobayashi
private Transform org;
//Kobayashi:Reference for "SpringManager" component with unitychan
private SpringManager managerRef;
private void Awake ()
{
trs = transform;
localRotation = transform.localRotation;
//Kobayashi:Reference for "SpringManager" component with unitychan
// GameObject.Find("unitychan_dynamic").GetComponent<SpringManager>();
managerRef = GetParentSpringManager (transform);
}
private SpringManager GetParentSpringManager (Transform t)
{
var springManager = t.GetComponent<SpringManager> ();
if (springManager != null)
return springManager;
if (t.parent != null) {
return GetParentSpringManager (t.parent);
}
return null;
}
private void Start ()
{
springLength = Vector3.Distance (trs.position, child.position);
currTipPos = child.position;
prevTipPos = child.position;
}
public void UpdateSpring ()
{
//Kobayashi
org = trs;
//回転をリセット
trs.localRotation = Quaternion.identity * localRotation;
float sqrDt = Time.deltaTime * Time.deltaTime;
//stiffness
Vector3 force = trs.rotation * (boneAxis * stiffnessForce) / sqrDt;
//drag
force += (prevTipPos - currTipPos) * dragForce / sqrDt;
force += springForce / sqrDt;
//前フレームと値が同じにならないように
Vector3 temp = currTipPos;
//verlet
currTipPos = (currTipPos - prevTipPos) + currTipPos + (force * sqrDt);
//長さを元に戻す
currTipPos = ((currTipPos - trs.position).normalized * springLength) + trs.position;
//衝突判定
for (int i = 0; i < colliders.Length; i++) {
if (Vector3.Distance (currTipPos, colliders [i].transform.position) <= (radius + colliders [i].radius)) {
Vector3 normal = (currTipPos - colliders [i].transform.position).normalized;
currTipPos = colliders [i].transform.position + (normal * (radius + colliders [i].radius));
currTipPos = ((currTipPos - trs.position).normalized * springLength) + trs.position;
}
}
prevTipPos = temp;
//回転を適用;
Vector3 aimVector = trs.TransformDirection (boneAxis);
Quaternion aimRotation = Quaternion.FromToRotation (aimVector, currTipPos - trs.position);
//original
//trs.rotation = aimRotation * trs.rotation;
//Kobayahsi:Lerp with mixWeight
Quaternion secondaryRotation = aimRotation * trs.rotation;
trs.rotation = Quaternion.Lerp (org.rotation, secondaryRotation, managerRef.dynamicRatio);
}
private void OnDrawGizmos ()
{
if (debug) {
Gizmos.color = Color.yellow;
Gizmos.DrawWireSphere (currTipPos, radius);
}
}
}
}
@@ -0,0 +1,10 @@
fileFormatVersion: 2
guid: 37b7c58dc2d739b4c90fe59f6875debf
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,25 @@
//
//SpringCollider for unity-chan!
//
//Original Script is here:
//ricopin / SpringCollider.cs
//Rocket Jump : http://rocketjump.skr.jp/unity3d/109/
//https://twitter.com/ricopin416
//
using UnityEngine;
using System.Collections;
namespace UnityChan
{
public class SpringCollider : MonoBehaviour
{
//半径
public float radius = 0.5f;
private void OnDrawGizmosSelected ()
{
Gizmos.color = Color.green;
Gizmos.DrawWireSphere (transform.position, radius);
}
}
}
@@ -0,0 +1,10 @@
fileFormatVersion: 2
guid: fcb73b690c023734fb267911061a15c6
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,83 @@
//
//SpingManager.cs for unity-chan!
//
//Original Script is here:
//ricopin / SpingManager.cs
//Rocket Jump : http://rocketjump.skr.jp/unity3d/109/
//https://twitter.com/ricopin416
//
//Revised by N.Kobayashi 2014/06/24
// Y.Ebata
//
using UnityEngine;
using System.Collections;
namespace UnityChan
{
public class SpringManager : MonoBehaviour
{
//Kobayashi
// DynamicRatio is paramater for activated level of dynamic animation
public float dynamicRatio = 1.0f;
//Ebata
public float stiffnessForce;
public AnimationCurve stiffnessCurve;
public float dragForce;
public AnimationCurve dragCurve;
public SpringBone[] springBones;
void Start ()
{
UpdateParameters ();
}
void Update ()
{
#if UNITY_EDITOR
//Kobayashi
if(dynamicRatio >= 1.0f)
dynamicRatio = 1.0f;
else if(dynamicRatio <= 0.0f)
dynamicRatio = 0.0f;
//Ebata
UpdateParameters();
#endif
}
private void LateUpdate ()
{
//Kobayashi
if (dynamicRatio != 0.0f) {
for (int i = 0; i < springBones.Length; i++) {
if (dynamicRatio > springBones [i].threshold) {
springBones [i].UpdateSpring ();
}
}
}
}
private void UpdateParameters ()
{
UpdateParameter ("stiffnessForce", stiffnessForce, stiffnessCurve);
UpdateParameter ("dragForce", dragForce, dragCurve);
}
private void UpdateParameter (string fieldName, float baseValue, AnimationCurve curve)
{
var start = curve.keys [0].time;
var end = curve.keys [curve.length - 1].time;
//var step = (end - start) / (springBones.Length - 1);
var prop = springBones [0].GetType ().GetField (fieldName, System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public);
for (int i = 0; i < springBones.Length; i++) {
//Kobayashi
if (!springBones [i].isUseEachBoneForceSettings) {
var scale = curve.Evaluate (start + (end - start) * i / (springBones.Length - 1));
prop.SetValue (springBones [i], baseValue * scale);
}
}
}
}
}
@@ -0,0 +1,10 @@
fileFormatVersion: 2
guid: 6514ba86f976d724ab63844a6015b2aa
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,83 @@
//
// Unityちゃん用の三人称カメラ
//
// 2013/06/07 N.Kobyasahi
//
using UnityEngine;
using System.Collections;
namespace UnityChan
{
public class ThirdPersonCamera : MonoBehaviour
{
public float smooth = 3f; // カメラモーションのスムーズ化用変数
Transform standardPos; // the usual position for the camera, specified by a transform in the game
Transform frontPos; // Front Camera locater
Transform jumpPos; // Jump Camera locater
// スムーズに繋がない時(クイック切り替え)用のブーリアンフラグ
bool bQuickSwitch = false; //Change Camera Position Quickly
void Start ()
{
// 各参照の初期化
standardPos = GameObject.Find ("CamPos").transform;
if (GameObject.Find ("FrontPos"))
frontPos = GameObject.Find ("FrontPos").transform;
if (GameObject.Find ("JumpPos"))
jumpPos = GameObject.Find ("JumpPos").transform;
//カメラをスタートする
transform.position = standardPos.position;
transform.forward = standardPos.forward;
}
void FixedUpdate () // このカメラ切り替えはFixedUpdate()内でないと正常に動かない
{
if (Input.GetButton ("Fire1")) { // left Ctlr
// Change Front Camera
setCameraPositionFrontView ();
} else if (Input.GetButton ("Fire2")) { //Alt
// Change Jump Camera
setCameraPositionJumpView ();
} else {
// return the camera to standard position and direction
setCameraPositionNormalView ();
}
}
void setCameraPositionNormalView ()
{
if (bQuickSwitch == false) {
// the camera to standard position and direction
transform.position = Vector3.Lerp (transform.position, standardPos.position, Time.fixedDeltaTime * smooth);
transform.forward = Vector3.Lerp (transform.forward, standardPos.forward, Time.fixedDeltaTime * smooth);
} else {
// the camera to standard position and direction / Quick Change
transform.position = standardPos.position;
transform.forward = standardPos.forward;
bQuickSwitch = false;
}
}
void setCameraPositionFrontView ()
{
// Change Front Camera
bQuickSwitch = true;
transform.position = frontPos.position;
transform.forward = frontPos.forward;
}
void setCameraPositionJumpView ()
{
// Change Jump Camera
bQuickSwitch = false;
transform.position = Vector3.Lerp (transform.position, jumpPos.position, Time.fixedDeltaTime * smooth);
transform.forward = Vector3.Lerp (transform.forward, jumpPos.forward, Time.fixedDeltaTime * smooth);
}
}
}
@@ -0,0 +1,10 @@
fileFormatVersion: 2
guid: bd9604897707c4879978b864a8be4d39
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,201 @@
//
// Mecanimのアニメーションデータが、原点で移動しない場合の Rigidbody付きコントローラ
// サンプル
// 2014/03/13 N.Kobyasahi
//
using UnityEngine;
using System.Collections;
namespace UnityChan
{
// 必要なコンポーネントの列記
[RequireComponent(typeof(Animator))]
[RequireComponent(typeof(CapsuleCollider))]
[RequireComponent(typeof(Rigidbody))]
public class UnityChanControlScriptWithRgidBody : MonoBehaviour
{
public float animSpeed = 1.5f; // アニメーション再生速度設定
public float lookSmoother = 3.0f; // a smoothing setting for camera motion
public bool useCurves = true; // Mecanimでカーブ調整を使うか設定する
// このスイッチが入っていないとカーブは使われない
public float useCurvesHeight = 0.5f; // カーブ補正の有効高さ(地面をすり抜けやすい時には大きくする)
// 以下キャラクターコントローラ用パラメタ
// 前進速度
public float forwardSpeed = 7.0f;
// 後退速度
public float backwardSpeed = 2.0f;
// 旋回速度
public float rotateSpeed = 2.0f;
// ジャンプ威力
public float jumpPower = 3.0f;
// キャラクターコントローラ(カプセルコライダ)の参照
private CapsuleCollider col;
private Rigidbody rb;
// キャラクターコントローラ(カプセルコライダ)の移動量
private Vector3 velocity;
// CapsuleColliderで設定されているコライダのHeiht、Centerの初期値を収める変数
private float orgColHight;
private Vector3 orgVectColCenter;
private Animator anim; // キャラにアタッチされるアニメーターへの参照
private AnimatorStateInfo currentBaseState; // base layerで使われる、アニメーターの現在の状態の参照
private GameObject cameraObject; // メインカメラへの参照
// アニメーター各ステートへの参照
static int idleState = Animator.StringToHash ("Base Layer.Idle");
static int locoState = Animator.StringToHash ("Base Layer.Locomotion");
static int jumpState = Animator.StringToHash ("Base Layer.Jump");
static int restState = Animator.StringToHash ("Base Layer.Rest");
// 初期化
void Start ()
{
// Animatorコンポーネントを取得する
anim = GetComponent<Animator> ();
// CapsuleColliderコンポーネントを取得する(カプセル型コリジョン)
col = GetComponent<CapsuleCollider> ();
rb = GetComponent<Rigidbody> ();
//メインカメラを取得する
cameraObject = GameObject.FindWithTag ("MainCamera");
// CapsuleColliderコンポーネントのHeight、Centerの初期値を保存する
orgColHight = col.height;
orgVectColCenter = col.center;
}
// 以下、メイン処理.リジッドボディと絡めるので、FixedUpdate内で処理を行う.
void FixedUpdate ()
{
float h = Input.GetAxis ("Horizontal"); // 入力デバイスの水平軸をhで定義
float v = Input.GetAxis ("Vertical"); // 入力デバイスの垂直軸をvで定義
anim.SetFloat ("Speed", v); // Animator側で設定している"Speed"パラメタにvを渡す
anim.SetFloat ("Direction", h); // Animator側で設定している"Direction"パラメタにhを渡す
anim.speed = animSpeed; // Animatorのモーション再生速度に animSpeedを設定する
currentBaseState = anim.GetCurrentAnimatorStateInfo (0); // 参照用のステート変数にBase Layer (0)の現在のステートを設定する
rb.useGravity = true;//ジャンプ中に重力を切るので、それ以外は重力の影響を受けるようにする
// 以下、キャラクターの移動処理
velocity = new Vector3 (0, 0, v); // 上下のキー入力からZ軸方向の移動量を取得
// キャラクターのローカル空間での方向に変換
velocity = transform.TransformDirection (velocity);
//以下のvの閾値は、Mecanim側のトランジションと一緒に調整する
if (v > 0.1) {
velocity *= forwardSpeed; // 移動速度を掛ける
} else if (v < -0.1) {
velocity *= backwardSpeed; // 移動速度を掛ける
}
if (Input.GetButtonDown ("Jump")) { // スペースキーを入力したら
//アニメーションのステートがLocomotionの最中のみジャンプできる
if (currentBaseState.nameHash == locoState) {
//ステート遷移中でなかったらジャンプできる
if (!anim.IsInTransition (0)) {
rb.AddForce (Vector3.up * jumpPower, ForceMode.VelocityChange);
anim.SetBool ("Jump", true); // Animatorにジャンプに切り替えるフラグを送る
}
}
}
// 上下のキー入力でキャラクターを移動させる
transform.localPosition += velocity * Time.fixedDeltaTime;
// 左右のキー入力でキャラクタをY軸で旋回させる
transform.Rotate (0, h * rotateSpeed, 0);
// 以下、Animatorの各ステート中での処理
// Locomotion中
// 現在のベースレイヤーがlocoStateの時
if (currentBaseState.nameHash == locoState) {
//カーブでコライダ調整をしている時は、念のためにリセットする
if (useCurves) {
resetCollider ();
}
}
// JUMP中の処理
// 現在のベースレイヤーがjumpStateの時
else if (currentBaseState.nameHash == jumpState) {
cameraObject.SendMessage ("setCameraPositionJumpView"); // ジャンプ中のカメラに変更
// ステートがトランジション中でない場合
if (!anim.IsInTransition (0)) {
// 以下、カーブ調整をする場合の処理
if (useCurves) {
// 以下JUMP00アニメーションについているカーブJumpHeightとGravityControl
// JumpHeight:JUMP00でのジャンプの高さ(0〜1)
// GravityControl:1⇒ジャンプ中(重力無効)、0⇒重力有効
float jumpHeight = anim.GetFloat ("JumpHeight");
float gravityControl = anim.GetFloat ("GravityControl");
if (gravityControl > 0)
rb.useGravity = false; //ジャンプ中の重力の影響を切る
// レイキャストをキャラクターのセンターから落とす
Ray ray = new Ray (transform.position + Vector3.up, -Vector3.up);
RaycastHit hitInfo = new RaycastHit ();
// 高さが useCurvesHeight 以上ある時のみ、コライダーの高さと中心をJUMP00アニメーションについているカーブで調整する
if (Physics.Raycast (ray, out hitInfo)) {
if (hitInfo.distance > useCurvesHeight) {
col.height = orgColHight - jumpHeight; // 調整されたコライダーの高さ
float adjCenterY = orgVectColCenter.y + jumpHeight;
col.center = new Vector3 (0, adjCenterY, 0); // 調整されたコライダーのセンター
} else {
// 閾値よりも低い時には初期値に戻す(念のため)
resetCollider ();
}
}
}
// Jump bool値をリセットする(ループしないようにする)
anim.SetBool ("Jump", false);
}
}
// IDLE中の処理
// 現在のベースレイヤーがidleStateの時
else if (currentBaseState.nameHash == idleState) {
//カーブでコライダ調整をしている時は、念のためにリセットする
if (useCurves) {
resetCollider ();
}
// スペースキーを入力したらRest状態になる
if (Input.GetButtonDown ("Jump")) {
anim.SetBool ("Rest", true);
}
}
// REST中の処理
// 現在のベースレイヤーがrestStateの時
else if (currentBaseState.nameHash == restState) {
//cameraObject.SendMessage("setCameraPositionFrontView"); // カメラを正面に切り替える
// ステートが遷移中でない場合、Rest bool値をリセットする(ループしないようにする)
if (!anim.IsInTransition (0)) {
anim.SetBool ("Rest", false);
}
}
}
void OnGUI ()
{
GUI.Box (new Rect (Screen.width - 260, 10, 250, 150), "Interaction");
GUI.Label (new Rect (Screen.width - 245, 30, 250, 30), "Up/Down Arrow : Go Forwald/Go Back");
GUI.Label (new Rect (Screen.width - 245, 50, 250, 30), "Left/Right Arrow : Turn Left/Turn Right");
GUI.Label (new Rect (Screen.width - 245, 70, 250, 30), "Hit Space key while Running : Jump");
GUI.Label (new Rect (Screen.width - 245, 90, 250, 30), "Hit Spase key while Stopping : Rest");
GUI.Label (new Rect (Screen.width - 245, 110, 250, 30), "Left Control : Front Camera");
GUI.Label (new Rect (Screen.width - 245, 130, 250, 30), "Alt : LookAt Camera");
}
// キャラクターのコライダーサイズのリセット関数
void resetCollider ()
{
// コンポーネントのHeight、Centerの初期値を戻す
col.height = orgColHight;
col.center = orgVectColCenter;
}
}
}
@@ -0,0 +1,10 @@
fileFormatVersion: 2
guid: 9001bcbd91e76437cb0f52f12764f2f0
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant: