Unity3D_楼梯算法

最简单的45°楼梯和任意角度楼梯


45°的楼梯可以先建立一个预制件,然后通过预制件复制元件。

void Start () {
		for (int i=0; i<10; i++) {
			GameObject pedal = (GameObject)GameObject.Instantiate (pedalPrefab);
			pedal.transform.position = new Vector3(-5+i,-2+i,0);
		}
	} 

这是形成了楼梯的一边,同样的如果要做上下楼梯,那么减一下就可以了。得到下图:

Unity3D_楼梯算法_第1张图片Unity3D_楼梯算法_第2张图片Unity3D_楼梯算法_第3张图片

任意角度的楼梯,其实就是一个角度的转换问题。具体代码如下:

public class stairsCS : MonoBehaviour {
	public GameObject pedalPrefab;
	private float angle = 30;
	// Use this for initialization
	void Start () {
		for (int i=0; i<10; i++) {
			GameObject pedal = (GameObject)GameObject.Instantiate (pedalPrefab);
			//在C#里面它认的是弧度,不是角度。所以要除以180.
			float hudu = (angle/180)*Mathf.PI;
			float yy = i*Mathf.Tan(hudu);
			pedal.transform.position = new Vector3(-5+i,-2+yy,0);
		}
	} 

}
上面代码得到的是30°的楼梯:

Unity3D_楼梯算法_第4张图片
那么通过上面的任意角度楼梯,可不可以再做一个高低起伏的道路呢?

具体代码如下

public class stairsCS : MonoBehaviour {
	public GameObject pedalPrefab;
	private float angle = 30;

	// Use this for initialization
	void Start () {
		float hudu = (angle/180)*Mathf.PI;
		for (int i=0; i<10; i++) {
			GameObject pedal = (GameObject)GameObject.Instantiate (pedalPrefab);
			//在C#里面它认的是弧度,不是角度。所以要除以180.
			float yy = i*Mathf.Tan(hudu);
			pedal.transform.position = new Vector3(-5+i,-2+yy,0);
		}
		for (int j=0; j<10; j++) {
			GameObject pedal = (GameObject)GameObject.Instantiate (pedalPrefab);
			float distance = 5*Mathf.Tan(hudu);
			pedal.transform.position = new Vector3(5+j,distance,0);
		}
		for (int t=0; t<10; t++) {
			GameObject pedal = (GameObject)GameObject.Instantiate (pedalPrefab);
			float distance = 5*Mathf.Tan(hudu);
			float decline = distance - t*Mathf.Tan(hudu);
			pedal.transform.position = new Vector3(15+t,decline,0);
		}
	} 

}

最后结果如下:

Unity3D_楼梯算法_第5张图片




你可能感兴趣的:(Unity3D)