Unity案例——滾球遊戲

新建一個項目,在Assets裏建立子文件夾並保存場景。首先建立一個Plane做爲場景的地面並附上資源包裏Background的材質,而後建立一個空的遊戲對象,將其命名爲Wall,在它的目錄下建立4個Cube,調整它們的位置及大小以做爲場景的牆體。接着建立一個Cube小方塊,爲了讓小方塊旋轉起來,咱們須要編寫一個腳本,代碼以下:ide

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

public class RotatePickUp : MonoBehaviour {

	// Use this for initialization
	void Start () {
		
	}
	
	// Update is called once per frame
	void Update () {
		this.transform.Rotate(new Vector3(15,30,45)*Time.deltaTime);
	}
}

建立一個Sphere小球,爲它添加一個剛體Rigidbody,編寫一個腳本控制小球的移動,代碼以下:this

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class PlayerController : MonoBehaviour {
	public float speed;
	private Rigidbody rb;
	public Text countText;
	public Text winText;
	private int count;

	// Use this for initialization
	void Start () 
	{
		rb=GetComponent<Rigidbody>();
		count=0;
		winText.text="";
		SetCountText();
	}
    void FixedUpdate() 
	{
		float moveHorizontal=Input.GetAxis("Horizontal");
		float moveVertical=Input.GetAxis("Vertical");
		Vector3 movement=new Vector3(moveHorizontal,0,moveVertical);
		rb.AddForce(movement*speed);
	}
	
    void OnTriggerEnter(Collider other) 
	{
		if(other.gameObject.CompareTag ("Pick Up"))
		{
			other.gameObject.SetActive(false);
			count+=1;
			SetCountText();
		}
	}

	void SetCountText()
	{
		countText.text="Count:"+count.ToString();
		if(count>=12)
		{
			winText.text="You Win";
		}
	}
	// Update is called once per frame
	void Update () {
		
	}
}

關於小球的參數設置:code

建立一個腳原本使攝像機跟着小球一塊兒移動,代碼以下:orm

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

public class CameraController : MonoBehaviour 
{
     public GameObject player;
	 private Vector3 offset;
	 public GameObject pickupPfb;
	 private GameObject[] obj1;
	 private int objCount=0;
	// Use this for initialization
	void Start () 
	{
		offset=this.transform.position-player.transform.position;

        //自動生成12個小方塊
		obj1=new GameObject[12];
		for(objCount=0;objCount<12;objCount++)
		{
			obj1[objCount]=GameObject.Instantiate(pickupPfb);
			obj1[objCount].name="pickup"+objCount.ToString();
			obj1[objCount].transform.position=new Vector3(4*Mathf.Sin(Mathf.PI/6*objCount),1,4*Mathf.Cos(Mathf.PI/6*objCount));
		}
	}
	void LateUpdate() 
	{
		this.transform.position=player.transform.position +offset;
	}
	
	// Update is called once per frame
	void Update () 
	{
		
	}
}

關於攝像機的參數設置:對象

相關文章
相關標籤/搜索