您的位置:首页 > 移动开发 > Unity3D

Unity (三)

2015-08-06 22:21 561 查看
今天练习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不会立即摧毁括号内指定的对象,而是标记为要销毁的对象,待每帧结束时所有标记对象一同销毁;
    }
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: