今天練習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);
}
}
using UnityEngine;
using System.Collections;
public class Mover : MonoBehaviour
{
public float speed;
void Start() //函數中的代碼會在對象實例化的最前幀執行;
{
rigidbody.velocity = transform.forward * speed;
}
}
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不會立即摧毀括號內指定的對象,而是標記爲要銷燬的對象,待每幀結束時所有標記對象一同銷燬;
}
}