物体をスナップさせる処理
わかりやすく吸着コードを書いたサンプル(下の例とほぼ同じ内容)
using UnityEngine;
using System.Collections;
public class TimeTest : MonoBehaviour {
public GameObject go; // Use this for initialization void Start () { go = GameObject.Find("Cube"); } float stepTime; float fpsRatio; Vector3 posA = new Vector3(2,0,0); //ブラックホールの中心 Vector3 distance; // Update is called once per frame void Update () { stepTime = Time.deltaTime; fpsRatio = Time.deltaTime*60.0f; //1以上という場合はUpdate()処理が遅れているという事 //unityは秒間60フレームで動作している Update()は1秒間に60回呼ばれる為 //Time.deltaTime は 0.0165~ ぐらいになる Time.deltaTime*60.0f するとほぼ 1 になる distance = posA - go.transform.position; distance *= 0.25f; //最初が最大速度で徐々に遅く小さくなっていく float min =0.01f; //最小速度&距離 float max =0.4f; //最大速度&距離 //distanceが常に自分の位置に対して加算されるなら「distance.magnitude」は「スピード(時速)」とも言える if(distance.magnitude < min){ go.transform.position = posA; //完全吸着 }else{ if(distance.magnitude > max){ distance *= max / distance.magnitude; //速度を制限する(最大速度以上だせなくなる(一回分の移動距離も小さくなる)) } go.transform.position += distance * fpsRatio; //ブラックホールの中心に向かって一直線に進む } }
}
パズルのピースをスナップさせる処理のサンプル
case STEP.SNAPPING:{ //スナップ位置へ徐々に移動して近づく処理(完成の判定自体は行っていない) //unityは秒間60フレームで動作している Update()は1秒間に60回呼ばれる為 //Time.deltaTime は 0.0165~ ぐらいになる Time.deltaTime*60.0f するとほぼ 1 になる Vector3 distance; float fpsRatio; fpsRatio = 60.0f * Time.deltaTime; distance = snapTarget - this.transform.position; //snapTargetへ向かうベクトルが得られる distance *= 0.25f * fpsRatio; //ベクトルを1/4に float snapSpeedMin = 0.01f * fpsRatio; float snapSpeedMax = 0.08f * fpsRatio; //distanceが常に自分の位置に対して加算されるなら「distance.magnitude」は「スピード(時速)」とも言える if(distance.magnitude < snapSpeedMin){ this.transform.position = snapTarget; //スピードと距離が極小なら完成として完全に吸着 }else{ if(distance.magnitude > snapSpeedMax){ //スピードと距離がそれなりに遠ければ distance *= snapSpeedMax/distance.magnitude; //最大速度制限をかけたベクトルにする(この行は重要 vector3にfloatで掛算している点に注目) } this.transform.position = this.transform.position + distance;; } } break;
メニュー
- 最終更新:2014-06-13 12:02:45