Unity3d鏡頭範圍內移動。

1:經過1天的嘗試,最終還是使用Mathf.Clamp。

2:創建地形teriann.

3:鏡頭綁定到物體上,爲物體添加碰撞盒,剛體,選擇運動學。使它在碰撞後不會有力的作用。

4:在fixupdate中添加區域檢測。


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

[System.Serializable]
public class Boundary
{
	public float xMin, xMax, zMin, zMax;
}


public class move : MonoBehaviour {

	public int stepSize = 30;

	private Vector2 touchfirst = Vector2.zero;
	private Vector2 touchsecond = Vector2.zero;
	public Boundary boundary;
	// Use this for initialization
	void Start () {
	}
	
	// Update is called once per frame
	void Update () {

	}

	void OnGUI(){
		if (Event.current.type == EventType.mouseDown) {
			touchfirst = Event.current.mousePosition;
		}
		if (Event.current.type == EventType.mouseDrag) {
			touchsecond = Event.current.mousePosition;
			if(touchsecond.x < touchfirst.x){
				transform.Translate(new Vector3(stepSize,0,0));
//				GetComponent<Rigidbody> ().transform.Translate((new Vector3(stepSize,0,0)));
			}
			if(touchsecond.x > touchfirst.x){
				transform.Translate(new Vector3(-stepSize,0,0));
//				GetComponent<Rigidbody> ().velocity = Vector3.right * 100f;
			}
			if(touchsecond.y < touchfirst.y){
				transform.Translate(new Vector3(0,0,-stepSize));
//				GetComponent<Rigidbody> ().velocity = Vector3.up * 100f;
			}
			if(touchsecond.y > touchfirst.y){
				transform.Translate(new Vector3(0,0,stepSize));
//				GetComponent<Rigidbody> ().velocity = Vector3.down * 100f;
			}
			touchfirst = touchsecond;

		}
	}

	void FixedUpdate ()
	{
		Rigidbody rb = GetComponent<Rigidbody> ();
		if (rb != null) {
			rb.position = new Vector3
				(
					Mathf.Clamp (rb.position.x, boundary.xMin, boundary.xMax),
					903.0f,
					Mathf.Clamp (rb.position.z, boundary.zMin, boundary.zMax)
					);
		}
	}
}

這個方法雖然比較不智能但至少先實現了我想要的效果,嘎嘎。下一步就是在地形周圍添加盒子,省的以後地圖中的啥東西會移動出去。



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章