Unity (三)
2015-08-06 22:21
561 查看
今天练习SpaceShooter的案例。其中大部分是在Unity中对控件进行操作。代码比较简单,基本都是按照英文的原意表达。太晚了,我直接复制代码了。
1、主角飞机——PlayerController
2、行星和子弹的移动——Mover
3、行星自转——RandomRotator
4、子弹和行星移动边界——DestroyBoundary
5、行星和飞机,子弹和行星之间的碰撞销毁——DestroyByContact
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不会立即摧毁括号内指定的对象,而是标记为要销毁的对象,待每帧结束时所有标记对象一同销毁; } }
相关文章推荐
- unity3d 学习笔记(两)
- Unity3D EasyTouch使用教程包括实例资源
- unity AssetBundle的资源管理
- 通过Unity依赖注入
- 解决 unity 用 vs通过wifi 真机联调 一直连接不上
- unity, audio falloff
- unity 摄像头
- 【Unity】2D动画控制器详解
- Unity 2D动画控制器详解
- Unity State Machine
- unity第三方插件behavior designer心得
- [Unity]Sprite 2D精灵动画
- 使用unity发布PSVita应用遇到的问题
- Unity项目工程集成Mob社会化分享SDK(android篇)
- unity场景导出
- Unity内存申请和释放
- unity3d之协程
- Unity+Metaio +IOS Xcode编译出错
- Unity3D新手教学,让你十二小时,从入门到掌握!(一)
- Unity3D中隐藏与显示物体