Unity案例——打磚塊小遊戲

1.首先建立一個Plane,並賦上材質,調整Plane的位置以及大小ide

2.用Cube來建立牆體this

  • 建立1個Cube,併爲它賦上材質
  • 將Cube移動到Assets目錄下的prefab中,而後刪除Hierarchy窗口中的Cube
  • 建立一個空對象,將其命名爲Wall
  • 編寫一個Brick腳原本生成牆體,並將它綁到Wall上。代碼以下:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Brick : MonoBehaviour {
	public GameObject brick;
	private int columnNum=8;
	private int rowNum=6;
	// Use this for initialization
	void Start () {
		for(int i=0; i<rowNum; i++)
		{
			for(int j=0; j<columnNum; j++)
			{
				Instantiate(brick,new Vector3(j-5,i),Quaternion.identity);
			}
		}	
	}
	
	// Update is called once per frame
	void Update () {
		
	}
}

將Brick的值設爲Assets裏的Cube3d

3.用Sphere建立發射的物體code

  • 建立一個Sphere,將其命名爲Ball,併爲它賦上材質
  • 添加一個剛體Rigidbody
  • 將Ball移動到Assets目錄下的prefab中,而後刪除Hierarchy窗口中的Ball
  • 編寫一個將球發射出去的腳本,代碼以下:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Shoot : MonoBehaviour {
	public GameObject shootPos;
	private float force=1000;
	public Rigidbody shootBall;
	private float speed=0.1f;
	// Use this for initialization
	void Start () {
		
	}
	
	// Update is called once per frame
	void Update () {
		Rigidbody ball;
		if(Input.GetKeyDown(KeyCode.Space))
		{
			ball=Instantiate(shootBall,shootPos.transform.position,Quaternion.identity) as Rigidbody;
			ball.AddForce(force*ball.transform.forward);
		}
         
        //控制攝像機的移動
		if(Input.GetKey(KeyCode.LeftArrow))
		{
			this.transform.Translate(Vector3.left*speed);
		}
		else if(Input.GetKey(KeyCode.RightArrow))
		{
			this.transform.Translate(Vector3.right*speed);
		}
		else if(Input.GetKey(KeyCode.UpArrow))
		{
			this.transform.Translate(Vector3.up*speed);
		}
		else if(Input.GetKey(KeyCode.DownArrow))
		{
			this.transform.Translate(Vector3.down*speed);
		}
	}
}

4.編寫一個銷燬球的腳本,代碼以下:orm

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

public class BallDestroy : MonoBehaviour {

	// Use this for initialization
	void Start () {
		
	}
	
	// Update is called once per frame
	void Update () {
		Destroy(this.gameObject,3f);
	}
}
相關文章
相關標籤/搜索