Unity (三)

今天練習SpaceShooter的案例。其中大部分是在Unity中對控件進行操作。代碼比較簡單,基本都是按照英文的原意表達。太晚了,我直接複製代碼了。

1、主角飛機——PlayerController

using UnityEngine;
using System.Collections;

[System.Serializable]	//使得變量可以被Inspector界面獲得;

public class Boundary	//全局變量;
{
    public float xMin, xMax, zMin, zMax;
}

public class PlayerController : MonoBehaviour 
{
    public float speed;
    public float tilt;
    public Boundary boundary;

    public GameObject shot;
    public Transform ShotSpawn;
    public float fireRate;
    private float nextFire;

    // Update is called once per frame
    void Update()
    {
        if (Input.GetButton("Fire1") && Time.time > nextFire)
        {
            nextFire = Time.time + fireRate;
            Instantiate(shot, ShotSpawn.position, ShotSpawn.rotation);        //實例化一個物體,位置,發射角度;
        }
	}

    void FixedUpdate ()  //會在每個固定的物理步驟前自動調用;
    {
        float moveHorizontal = Input.GetAxis("Horizontal");
        float moveVertical = Input.GetAxis("Vertical");

        Vector3 movement= new Vector3(moveHorizontal,0.0f,moveVertical);
        rigidbody.velocity = movement * speed;

        rigidbody.position = new Vector3 
        (
            Mathf.Clamp(rigidbody.position.x, boundary.xMin, boundary.xMax),
            0.0f,
            Mathf.Clamp(rigidbody.position.z, boundary.zMin, boundary.zMax)
        );

        rigidbody.rotation = Quaternion.Euler(0.0f,0.0f,rigidbody.velocity.x * -tilt);
    }
}


2、行星和子彈的移動——Mover

using UnityEngine;
using System.Collections;



public class Mover : MonoBehaviour 
{
    public float speed;
    void Start()        //函數中的代碼會在對象實例化的最前幀執行;
    {
        rigidbody.velocity = transform.forward * speed;

    }
}


3、行星自轉——RandomRotator

using UnityEngine;
using System.Collections;

public class RandomRotator : MonoBehaviour
{
    public float tumble;

    void Start()
    {
        rigidbody.angularVelocity = Random.insideUnitSphere * tumble;
    }
}

4、子彈和行星移動邊界——DestroyBoundary

using UnityEngine;
using System.Collections;

public class DestroyBoundary : MonoBehaviour 
{
    void OnTriggerExit(Collider other)
    {
        Destroy(other.gameObject);
    }
}

5、行星和飛機,子彈和行星之間的碰撞銷燬——DestroyByContact

using UnityEngine;
using System.Collections;

public class DestroyByContact : MonoBehaviour 
{
    public GameObject explosion;
    public GameObject playerExplosion;

	void OnTriggerEnter(Collider other)
    {
        if (other.tag == "Boundary")
        {
            return;
        }

        Instantiate(explosion, transform.position, transform.rotation);

        if (other.tag == "Player")
        {
            Instantiate(playerExplosion, other.transform.position, other.transform.rotation);
        }
        
        Destroy(other.gameObject);
        Destroy(gameObject);        //Destroy不會立即摧毀括號內指定的對象,而是標記爲要銷燬的對象,待每幀結束時所有標記對象一同銷燬;
    }
}


發佈了21 篇原創文章 · 獲贊 6 · 訪問量 7萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章