今天無聊就根據這幾天學的東西做了一個小遊戲。
遊戲開始磚塊從天而降,玩家轉動滑鼠控制鏡頭,點擊滑鼠將磚塊打出邊界。很簡單的遊戲,做著玩的。
下面是需要添加在Main Camera上的代碼,用於移動滑鼠控制攝像機鏡頭
using UnityEngine;using System.Collections;//通過移動滑鼠左右控制攝像機public class CameraHelp : MonoBehaviour { //旋轉速度 public float rotate_Speed = 2f; // Update is called once per frame void Update () { //擷取滑鼠移動X距離 float mouseX = Input .GetAxis( "Mouse X") * rotate_Speed; //攝像機旋轉 transform.Rotate( new Vector3 (0, mouseX, 0)); }}
然後是添加一個Plane,添加在Plane上面的指令碼代碼
using UnityEngine;using System.Collections;public class GameInit : MonoBehaviour{ //產生方塊間隔 private int space; //顏色數組,用來產生不同的顏色 private Color [] mColors = new Color[] { Color .white, Color .yellow, Color.red, Color .blue, Color .green }; void Awake() { space = 0; //設定情境的重力 Physics .gravity = new Vector3(0, -1.0f, 0); } // Update is called once per frame void Update() { //檢測滑鼠左鍵是否按下 if (Input .GetMouseButtonDown(0)) { //建立一個小球模型 GameObject ball = GameObject .CreatePrimitive( PrimitiveType.Sphere); //初始小球位置為主攝像機位置 ball.transform.position = Camera .main.transform.position; //添加剛體組件 ball.AddComponent< Rigidbody >(); //添加自動銷毀指令碼 ball.AddComponent< AutoDestory >(); //點擊位置,將螢幕中滑鼠點擊位置轉變為全局座標 Vector3 target = Camera .main.ScreenToWorldPoint( new Vector3( Input .mousePosition.x, Input .mousePosition.y, 1)); //點擊位置與發射位置的方向向量 Vector3 direction = target - Camera .main.transform.position; //添加顏色 ball.renderer.material.color = mColors[ Random .Range(0, mColors.Length)]; //添加剛體力 ball.rigidbody.AddForce(direction * 10, ForceMode .VelocityChange); } } void FixedUpdate() { //每隔30幀繪製一個方塊,並從天上掉下 if (space == 30) { //建立一個方塊模型 GameObject mCube = GameObject .CreatePrimitive( PrimitiveType.Cube); //設定方塊顏色 mCube.renderer.material.color = mColors[ Random .Range(0, mColors.Length)]; //設定方塊初始位置 mCube.transform.position = new Vector3 ( Random.Range(5.5f, 14.5f), 8, 8); //添加剛體 mCube.AddComponent< Rigidbody >(); //添加自動銷毀指令碼 mCube.AddComponent< AutoDestory >(); //間隔清零 space = 0; } space++; }}
關於AutoDestory我自建了一個離開攝像機自動銷毀指令碼
using UnityEngine;using System.Collections;public class AutoDestory : MonoBehaviour { void OnBecameInvisible() { Destroy( this .gameObject); }}
看看運行後的效果吧
注釋寫的很詳細,就不用多說了。這純屬個人覺得好玩,粗糙的地方見諒。