http://pixelnest.io/tutorials/2d-game-unity/player-and-enemies/
根据官网的飞机教程
建立好scenes
给player绑定刚体代码
通过方向键控制刚体速度
using UnityEngine; using System.Collections; public class PlayerScript : MonoBehaviour { // Use this for initialization void Start () { print("启动!"); } public Vector2 speed = new Vector2(10, 10); public Vector2 movement; public Rigidbody2D rigidbodyComponent; // Update is called once per frame void Update () { float inputX = Input.GetAxis("Horizontal"); float inputY = Input.GetAxis("Vertical"); movement = new Vector2( speed.x * inputX, speed.y * inputY ); } void FixedUpdate() { if (rigidbodyComponent == null) rigidbodyComponent = GetComponent<Rigidbody2D>(); rigidbodyComponent.velocity = movement; } void Awake() { print("我是构造函数"); } }
Input.GetAxis是捕获键盘上的操作
Rigidbody2D.velocity 速度
http://wiki.ceeger.com/script/unityengine/classes/rigidbody2d/rigidbody2d.velocity移动脚本:
using UnityEngine; using System.Collections; public class MoveScript : MonoBehaviour { public Vector2 movement; public Vector2 speed = new Vector2(-2, 0); // Use this for initialization void Start () { } // Update is called once per frame void Update () { movement = new Vector2( speed.x * 1, speed.y * 0 ); } void FixedUpdate() { rigidbody2D.velocity = movement; } }
血量脚本:
using UnityEngine; using System.Collections; public class HealthScript : MonoBehaviour { public int hp = 1; public bool isEnemy = true; public void Damage(int damageCount){ hp -= damageCount; if(hp <= 0){ Destroy(gameObject); } } void OnTriggerEnter2D(Collider2D otherCollider){ ShotScript shot = otherCollider.gameObject.GetComponent<ShotScript>(); if (shot != null) { if(shot.isEnemyShot != isEnemy){ Damage(shot.damage); Destroy(shot.gameObject); } } } }
Destroy(shot.gameObject);
代表删除一个游戏内对象
启动的时候有个很奇怪的BUG 子弹会往上飘一下 。。
找到原因了 是因为在U3D里面给属性赋值了15,15 初始值位移偏移量
开始写开火脚本:
using UnityEngine; /// <summary> /// Launch projectile /// </summary> public class WeaponScript : MonoBehaviour { //-------------------------------- // 1 - Designer variables //-------------------------------- /// <summary> /// Projectile prefab for shooting /// </summary> public Transform shotPrefab; /// <summary> /// Cooldown in seconds between two shots /// </summary> public float shootingRate = 0.25f; //-------------------------------- // 2 - Cooldown //-------------------------------- private float shootCooldown; void Start() { shootCooldown = 0f; } void Update() { if (shootCooldown > 0) { shootCooldown -= Time.deltaTime; } } //-------------------------------- // 3 - Shooting from another script //-------------------------------- /// <summary> /// Create a new projectile if possible /// </summary> public void Attack(bool isEnemy) { if (CanAttack) { shootCooldown = shootingRate; // Create a new shot var shotTransform = Instantiate(shotPrefab) as Transform; // Assign position shotTransform.position = transform.position; // The is enemy property ShotScript shot = shotTransform.gameObject.GetComponent<ShotScript>(); if (shot != null) { shot.isEnemyShot = isEnemy; } // Make the weapon shot always towards it MoveScript move = shotTransform.gameObject.GetComponent<MoveScript>(); if (move != null) { move.direction = this.transform.right; // towards in 2D space is the right of the sprite } } } /// <summary> /// Is the weapon ready to create a new projectile? /// </summary> public bool CanAttack { get { return shootCooldown <= 0f; } } }
Transform:
游戏对象的Transform
Transform属性可以进行位置、旋转、大小的设置
位置:position
旋转:rotate
大小:localScale
如果要操作脚本当前使用的GameObject,则可以省略要操作的GameObjiect.
Time.deltaTime
https://blog.csdn.net/wdjhzw/article/details/73433658?locationNum=7&fps=1
使用标准的包可以阻止你的想法,也不会让你的游戏脱颖而出。
这句话应该为每个游戏开发者铭记
using UnityEngine; public static class RendererExtensions { public static bool IsVisibleFrom(this Renderer renderer, Camera camera) { Plane[] planes = GeometryUtility.CalculateFrustumPlanes(camera); return GeometryUtility.TestPlanesAABB(planes, renderer.bounds); } }
扩展摄像头
using UnityEngine; /// <summary> /// Creating instance of particles from code with no effort /// </summary> public class SpecialEffectsHelper : MonoBehaviour { /// <summary> /// Singleton /// </summary> public static SpecialEffectsHelper Instance; public ParticleSystem smokeEffect; public ParticleSystem fireEffect; void Awake() { // Register the singleton if (Instance != null) { Debug.LogError("Multiple instances of SpecialEffectsHelper!"); } Instance = this; } /// <summary> /// Create an explosion at the given location /// </summary> /// <param name="position"></param> public void Explosion(Vector3 position) { // Smoke on the water instantiate(smokeEffect, position); // Tu tu tu, tu tu tudu // Fire in the sky instantiate(fireEffect, position); } /// <summary> /// Instantiate a Particle system from prefab /// </summary> /// <param name="prefab"></param> /// <returns></returns> private ParticleSystem instantiate(ParticleSystem prefab, Vector3 position) { ParticleSystem newParticleSystem = Instantiate( prefab, position, Quaternion.identity ) as ParticleSystem; // Make sure it will be destroyed Destroy( newParticleSystem.gameObject, newParticleSystem.startLifetime ); return newParticleSystem; } }
调用爆炸粒子的代码有个bug 找不到原因...
添加音频
using UnityEngine; using System.Collections; /// <summary> /// 创建音效实例 /// </summary> public class SoundEffectsHelper : MonoBehaviour { /// <summary> /// 静态实例 /// </summary> public static SoundEffectsHelper Instance; public AudioClip explosionSound; public AudioClip playerShotSound; public AudioClip enemyShotSound; void Awake() { // 注册静态实例 if (Instance != null) { Debug.LogError("Multiple instances of SoundEffectsHelper!"); } Instance = this; } public void MakeExplosionSound() { MakeSound(explosionSound); } public void MakePlayerShotSound() { MakeSound(playerShotSound); } public void MakeEnemyShotSound() { MakeSound(enemyShotSound); } /// <summary> /// 播放给定的音效 /// </summary> /// <param name="originalClip"></param> private void MakeSound(AudioClip originalClip) { // 做一个非空判断, 防止异常导致剩余操作被中止 if (Instance.ToString() != "null") { // 因为它不是3D音频剪辑,位置并不重要。 AudioSource.PlayClipAtPoint(originalClip, transform.position); } } }
射击音效
if (isEnemy) { SoundEffectsHelper.Instance.MakeEnemyShotSound(); } else { SoundEffectsHelper.Instance.MakePlayerShotSound(); }赋值: