网站建设定制开发2D游戏案例:Ruby‘s Adventure

网站建设定制开发程序文件打包:

链接:https://pan.baidu.com/s/1wyV_4k45eXhzrrq0_CVfQw 
提取码:olhi

目录

第一步:导入素材

第二步:网站建设定制开发网站建设定制开发编写第一个脚本

第三步:网站建设定制开发网站建设定制开发绘制游戏场景 

第四步:网站建设定制开发实现相机跟随

第五步:网站建设定制开发采集生命道具

第六步:伤害检测

第七步:网站建设定制开发引入敌人元素

第八步:网站建设定制开发添加物品动画

第九步:网站建设定制开发添加敌人动画

第十步:网站建设定制开发添加玩家动画

第十一步:发射子弹

第十二步:网站建设定制开发增添敌人特效

第十三步:网站建设定制开发增添物品特效

第十四步:显示血条

第十五步:网站建设定制开发增加场景音乐

第十六步:创建NPC

第十七步:网站建设定制开发创建子弹补给

第十八步:打包安装


正片开始。

第一步:导入素材

(1)目的:获取官方’s Adventure游戏资源。

(2)方法:网站建设定制开发点击上方菜单栏:window -> Asset Store -> Search:Ruby -> Import

(3)注意:网站建设定制开发要把所有资源一次性全部导入。

第二步:编写第一个脚本

(1)目的:网站建设定制开发测试游戏角色是否能够移动

(2)方法:

        1、网站建设定制开发在素材文件夹(Art->Spirits->Characters)网站建设定制开发中拖拽一张Ruby网站建设定制开发图片到左侧的任务区,网站建设定制开发默认为角色对象。

        2、在Asset网站建设定制开发网站建设定制开发文件夹中新建Scripts网站建设定制开发脚本文件夹。

        3、在Scripts文件夹中新建C#脚本,命名为PlayerController(网站建设定制开发程序员可自行更改)。

        4、编写脚本:网站建设定制开发是网站建设定制开发角色向右移动。

  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. /// <summary>
  5. /// 网站建设定制开发网站建设定制开发网站建设定制开发控制角色移动、生命、动画等
  6. /// </summary>
  7. public class PlayerController : MonoBehaviour
  8. {
  9. public float speed = 5f;//移动速度
  10. // Start is called before the first frame update
  11. void Start()
  12. {
  13. }
  14. // Update is called once per frame
  15. void Update()
  16. {
  17. transform.Translate(transform.right * speed * Time.deltaTime);//角色向右移动,Time.deltaTime-网站建设定制开发是计算机渲染一
  18. }
  19. }

        5、网站建设定制开发将写好的脚本挂给角色属性栏。点击播放,就能看到Ruby网站建设定制开发开始移动了。

示例:

6、网站建设定制开发测试移动脚本-1 通过awsd(网站建设定制开发或四个方向键)控制角色移动。

  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. /// <summary>
  5. /// 控制角色移动、生命、动画等
  6. /// </summary>
  7. public class PlayerController : MonoBehaviour
  8. {
  9. public float speed = 5f;//移动速度
  10. // Start is called before the first frame update
  11. void Start()
  12. {
  13. }
  14. // Update is called once per frame
  15. void Update()
  16. {
  17. float moveX = Input.GetAxisRaw("Horizontal");//网站建设定制开发控制水平移动方向 A:-1 D:1 不按: 0
  18. float moveY = Input.GetAxisRaw("Vertical");//网站建设定制开发控制垂直移动方向 W:-1 S:1 不按: 0
  19. Vector2 position = transform.position;//网站建设定制开发定义角色位置向量
  20. position.x += moveX * speed * Time.deltaTime;
  21. position.y += moveY * speed * Time.deltaTime;
  22. transform.position = position;//网站建设定制开发将位置信息传输给角色
  23. }
  24. }

第三步:绘制游戏场景 
 

(1)目的:网站建设定制开发给游戏画面增添地图场景。

(2)方法:

        1、网站建设定制开发鼠标在左侧任务区点击右键,选择创建 2D Object。

        2、网站建设定制开发任务栏中出现 Grid文件夹,网站建设定制开发里面有一个Tilemap文件。Tilemap网站建设定制开发就是帮助我们实现画图的工具。

        3、点击资源文件夹 Art->Spirits->Environment,找到想要绘制的场景图片。

        4、创建第一张贴图:先在Asset文件夹下创建一个新的文件夹叫Tiles来存放图片信息。点开Tiles文件,右键,点击Tile,创建第一块贴图,起名叫FirstTile。此时下面的Tiles文件夹中就会出一张瓦片贴图。

        5、裁剪图片:将一张图分解成3*3的图片。(1) 找到你要裁剪的图片,观察右侧图片的参数信息,找到Sprite Mode 将single(默认)调成Mutiple。再点击下方的Sprite Editor (精灵编辑)。出现切割界面后点击左上角Slice->Type->Grid by cell Count(按数量切割) 更改参数R (row):3C(clumn):3,切好后点击右上角 Apply 应用完成,关闭界面。切割好一个后,其余的地面图片也要进行切割,所以选择头图片按住shift键再选择尾图片修改Spite Mode为Multiple,点击下方Aply,这样就完成了批量更改精灵模式操作,接下来在进行依次切割就可以了。

裁剪完的示意图:

        6、创建贴图调色板:点击上方菜单栏:Window->2D->Tile Pallet。这时调色板就已经出现了,点击新建,重新命名Game Pallet。保存在Tiles文件夹下,这样一个新的调色板就建好了。然后将想要绘制的图片直接拖入调色板中,(这里需要注意的是,在选择文件夹时我们的瓦片信息都是存放在Tiles文件夹下的,)然后选择图块用调色板上方的笔刷功能就可以进行绘制了。

调色板准备就绪:

        

7、使贴图占满整格:在刚开始绘制的时候,一般都会遇到这种现象,就是,图片的大小与网格大小不匹配,格子与格子之间有空隙。这是就需要我们手动计算调整一下图片尺寸了。点击原图,查看属性右侧上方,Pixels Per Unit :100(一个格子占长宽是100个像素)在看一下右侧下方原图属性:192*192,每一块边长是192个像素,分成9块后,每一块边长就是64,所64<100,格子无法占满。也就是说,只要我们把每个格子100个像素改成每个格子64个像素就能实现图片填满的效果了,最后不要忘了点击aply。

        8、给物体增加碰撞和物理刚体:首先选择一个对象,点击右侧栏下Add Component(增添组件),搜索Box Collider 2D ,再点击 Edit Collider给物体会发生碰撞的位置做一个选区即可。

        9、给角色增加物理刚体:点击角色对象,在右侧信息栏中点击Add Component,搜索Ragidbody 2D, 点击后角色就增加了物理属性,因为我们做的是2D游戏,所以添加了物理缸体后要将重力加速度的勾选去掉,否则角色就会一直下落。

        10、丰富我们的场景:一个物体一个物体的绘制相当麻烦,为了方便我们实现克隆式的批量操作,我们先在Asset文件夹中建立一个新的文件夹Prefab(预制体)。先拖拽出一个物体设置好它的属性后将其拖入Prefab文件夹,然后在将它从Prefab文件中拖出,发现字体都是蓝色,那就说明预制体设置成功,每一个从Prefab文件夹里拖出的复制品都有相同的属性。(友情提示:在设置物体属性时最好是调整好属性之后在进行拖拽进Prefab中去,这真的挺重要的我觉得。。。)

        11、利用图层排序实现物体遮挡效果:Edit->Project Settings->Graphics      再点击Transparency Sort Mode 选择Custom Axis(自定义轴) 将参数改成 X :0   Y:1    Z:0   改好之后点击Ctrl + s保存设置(这个过程必须是非演示时才能生效),回到主界面,点击角色和物体图层,必须保证角色和物体图层为同一层级时才能实现遮挡。

        12、解决角色与物体碰撞发生的抖动与旋转问题。旋转问题非常好解决,首先判断发生旋转的原因,因为角色挂上了物理刚体组件,所以碰撞会产生弹力因为受力不均就会发生旋转,那么解决的办法是,点击角色查看属性,找到刚体属性,再限制绕z轴旋转即可。解决角色抖动,只需要把脚本中的角色位置传输改成刚体即可。

        13、编写角色脚本(引入物体刚体组件):

  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. /// <summary>
  5. /// 控制角色移动、生命、动画等
  6. /// </summary>
  7. public class PlayerController : MonoBehaviour
  8. {
  9. public float speed = 5f;//移动速度
  10. Rigidbody2D rbody;//刚体组件
  11. // Start is called before the first frame update
  12. void Start()
  13. {
  14. rbody = GetComponent<Rigidbody2D>();
  15. }
  16. // Update is called once per frame
  17. void Update()
  18. {
  19. float moveX = Input.GetAxisRaw("Horizontal");//控制水平移动方向 A:-1 D:1 不按: 0
  20. float moveY = Input.GetAxisRaw("Vertical");//控制垂直移动方向 W:-1 S:1 不按: 0
  21. //================移动================================================
  22. Vector2 position = rbody.position;//定义角色位置向量
  23. position.x += moveX * speed * Time.deltaTime;
  24. position.y += moveY * speed * Time.deltaTime;
  25. rbody.MovePosition(position);//将位置信息传输给角色
  26. }
  27. }

(3)注意:如果任务列表中东西太多,可以新建一个New Empty用来专门存放这些物体。

      

第四步:实现相机跟随

(1)目的:使相机跟随角色移动。

(2)方法:

        1、下载相机组件:(否则的话要自己编写代码)

        2、点击上方菜单栏:Window->Package Manner->all package->cinemachine->install

        3、组件下载完之后,上方菜单栏会出现Cinemachine(本教程使用2.2.9版本),点击后选择cinema 2D创建一个2D相机。

        4、再将Ruby拖拽到相机属性的follow一栏中,就能实现玩家跟随了。视角大小可以在属性栏中修改。

        5、限制角色在地图上的活动范围:点击Tilemap,属性中增加 Tilemap Collider 2D,现在角色无法移动,因为周围都是绿格子(碰撞盒)。然后点击Tile文件夹,将所有不包含水面的图片选择中,将右侧信息栏中的collider type改成None,这样就实现了除水面随便走的情况。

        6、为了节省性能,通常我们会选择碰撞格的合并:在Tilemap里添加组件composite 组件,之后会出现一个刚体属性,将刚体属性的重力加速度归零,在把composite勾选,这样碰撞盒就能合并了,减少性能消耗。如果你的地图会抖动,那么就将xyz轴的限制框选都勾上或者将刚体设置成 Static 静态。

        7、设置相机边界:点击左侧任务栏中的相机对象,观察右侧属性栏下方有一个Add Extension选择CinemachineConfiner,点击添加。然后在左侧任务栏右键Create Empty,命名为CameraConfiner,右侧新增属性Add component,搜索Polygon Collider 2D,拖点编辑范围即可,最后将编辑好的组件,拖入到相机属性的Extensions的选窗里即可(Bounding Shape 2D)。设置完边界后,不出意外,你的角色是看不到的,因为他被相机刚体挤到了外面,这时把CameraConfiner属性栏中的isTrigger勾选上即可。

 相机边界绿线:

第五步:采集生命道具

(1)目的:增加草莓物体,恢复角色血量。        

(2)方法:

        1、在素材中选择草莓,拖拽进左边任务栏中,点击草莓原图,更改草莓属性大小,调到合适位置即可。然后增加碰撞属性(box collider 2D),为了让角色能穿过草莓,在草莓的box collider 属性栏里勾选is trigger,这样角色就能穿过草莓了。

        2、编写拾取草莓脚本:用触发碰撞函数确定角色和草莓相撞。

  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. /// <summary>
  5. /// 草莓被玩家碰撞时检测的相关
  6. /// </summary>
  7. public class Collectible : MonoBehaviour
  8. {
  9. // Start is called before the first frame update
  10. void Start()
  11. {
  12. }
  13. // Update is called once per frame
  14. void Update()
  15. {
  16. }
  17. /// <summary>
  18. /// 碰撞检测相关
  19. /// </summary>
  20. void OnTriggerEnter2D(Collider2D other)
  21. {
  22. PlayerController pc = other.GetComponent<PlayerController>();
  23. if(pc != null)
  24. {
  25. Debug.Log("玩家碰到了草莓!");
  26. }
  27. }
  28. }

        3、玩家脚本的更改:因为在血量不足的情况下才会拾取草莓,所以 Collectible这个类中药访问到玩家的血量。

  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. /// <summary>
  5. /// 控制角色移动、生命、动画等
  6. /// </summary>
  7. public class PlayerController : MonoBehaviour
  8. {
  9. public float speed = 5f;//移动速度
  10. private int maxHealth = 5;//最大生命值
  11. private int currentHealth;//当前生命值
  12. //访问私有变量的两个函数
  13. public int MyMaxHealth { get { return maxHealth; } }
  14. public int MyCurrentHealth { get { return currentHealth; } }
  15. Rigidbody2D rbody;//刚体组件
  16. // Start is called before the first frame update
  17. void Start()
  18. {
  19. currentHealth = 2;//设置初始血量为2
  20. rbody = GetComponent<Rigidbody2D>();
  21. }
  22. // Update is called once per frame
  23. void Update()
  24. {
  25. float moveX = Input.GetAxisRaw("Horizontal");//控制水平移动方向 A:-1 D:1 不按: 0
  26. float moveY = Input.GetAxisRaw("Vertical");//控制垂直移动方向 W:-1 S:1 不按: 0
  27. //================移动================================================
  28. Vector2 position = rbody.position;//定义角色位置向量
  29. position.x += moveX * speed * Time.deltaTime;
  30. position.y += moveY * speed * Time.deltaTime;
  31. rbody.MovePosition(position);//将位置信息传输给角色
  32. }
  33. /// <summary>
  34. /// 改变玩家的生命值
  35. /// </summary>
  36. public void ChangeHealth(int amount)
  37. {
  38. Debug.Log(currentHealth + "/" + maxHealth);
  39. //把玩家的生命值约束在0到最大值之间
  40. currentHealth = Mathf.Clamp(currentHealth + amount, 0, maxHealth);
  41. Debug.Log(currentHealth + "/" + maxHealth);
  42. }
  43. }

        4、更改草莓脚本:当检测到草莓被拾取时,销毁草莓对象。

  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. /// <summary>
  5. /// 草莓被玩家碰撞时检测的相关
  6. /// </summary>
  7. public class Collectible : MonoBehaviour
  8. {
  9. // Start is called before the first frame update
  10. void Start()
  11. {
  12. }
  13. // Update is called once per frame
  14. void Update()
  15. {
  16. }
  17. /// <summary>
  18. /// 碰撞检测相关
  19. /// </summary>
  20. void OnTriggerEnter2D(Collider2D other)
  21. {
  22. PlayerController pc = other.GetComponent<PlayerController>();
  23. if(pc != null)
  24. {
  25. if(pc.MyCurrentHealth < pc.MyMaxHealth)
  26. {
  27. pc.ChangeHealth(1);//血量加一
  28. Destroy(this.gameObject);//加完血后草莓消失
  29. }
  30. }
  31. }
  32. }

        5、接下来将草莓设为预制体,复制多个。

碰撞检测成功:

第六步:伤害检测

        (1)目的:设置陷阱,是角色减血,增加游戏困难度。

        (2)方法:

                1、找到素材里的陷阱图片,拖拽到任务栏,添加碰撞属性,勾选is Trigger。

                2、给陷阱添加脚本:如果玩家与陷阱发生碰撞,玩家生命值减1.

  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. /// <summary>
  5. /// 伤害陷阱相关
  6. /// </summary>
  7. public class DamageArea : MonoBehaviour
  8. {
  9. void OnTriggerStay2D(Collider2D other)
  10. {
  11. PlayerController pc = other.GetComponent<PlayerController>();
  12. if (pc != null)
  13. {
  14. pc.ChangeHealth(-1);
  15. }
  16. }
  17. }

        3、更改玩家脚本:玩家踩到陷阱受到一次伤害,玩家持续踩陷阱,每隔两秒受到一次伤害。2秒成为无敌时间。

  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. /// <summary>
  5. /// 控制角色移动、生命、动画等
  6. /// </summary>
  7. public class PlayerController : MonoBehaviour
  8. {
  9. public float speed = 5f;//移动速度
  10. private int maxHealth = 5;//最大生命值
  11. private int currentHealth;//当前生命值
  12. //访问私有变量的两个函数
  13. public int MyMaxHealth { get { return maxHealth; } }
  14. public int MyCurrentHealth { get { return currentHealth; } }
  15. private float invincibleTime = 2f;//无敌时间两秒
  16. private float invicibleTimer;//无敌计时器
  17. private bool isInvincible;//是否处于无敌状态
  18. Rigidbody2D rbody;//刚体组件
  19. // Start is called before the first frame update
  20. void Start()
  21. {
  22. currentHealth = 2;//设置初始血量为2
  23. invicibleTimer = 0;
  24. rbody = GetComponent<Rigidbody2D>();
  25. }
  26. // Update is called once per frame
  27. void Update()
  28. {
  29. float moveX = Input.GetAxisRaw("Horizontal");//控制水平移动方向 A:-1 D:1 不按: 0
  30. float moveY = Input.GetAxisRaw("Vertical");//控制垂直移动方向 W:-1 S:1 不按: 0
  31. //================移动================================================
  32. Vector2 position = rbody.position;//定义角色位置向量
  33. position.x += moveX * speed * Time.deltaTime;
  34. position.y += moveY * speed * Time.deltaTime;
  35. rbody.MovePosition(position);//将位置信息传输给角色
  36. //==================无敌计时==============================================
  37. if (isInvincible)
  38. {
  39. invicibleTimer -= Time.deltaTime;
  40. if(invicibleTimer < 0)
  41. {
  42. isInvincible = false;//倒计时结束后取消无敌状态
  43. }
  44. }
  45. }
  46. /// <summary>
  47. /// 改变玩家的生命值
  48. /// </summary>
  49. public void ChangeHealth(int amount)
  50. {
  51. if(amount < 0)
  52. {
  53. if (isInvincible == true)
  54. return;
  55. isInvincible = true;
  56. invicibleTimer = invincibleTime;
  57. }
  58. Debug.Log(currentHealth + "/" + maxHealth);
  59. //把玩家的生命值约束在0到最大值之间
  60. currentHealth = Mathf.Clamp(currentHealth + amount, 0, maxHealth);
  61. Debug.Log(currentHealth + "/" + maxHealth);
  62. }
  63. }

*注意:做好之后,会发现一个bug,就是当玩家站在陷阱中不动时,血量不会减少。改正:左侧任务栏点击玩家,查看属性在刚体栏中,找到Sleeping Mode,并选择Never Sleep,这样就能解决上述问题了。

        4、陷阱区域的放大缩小:点击陷阱对象,右侧属性栏Draw Mode选择Tiled,点击下方文件夹中的图片将属性Mesh Type改成Full Rect。点击应用即可。缩放的时候选择工具rect tool 拉扯图形边框才能缩放,其他方式不行。

第七步:引入敌人元素

(1)目的:增强游戏趣味性。

(2)方法:

        1、将敌人图片拖入任务栏,命名为Robot,给敌人属性加入Rigidbody 2D(物理刚体) 和box collider 2D(碰撞盒)。

        2、加入机器人移动脚本 : 机器人向上或向右移动脚本:

  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. /// <summary>
  5. /// 敌人控制相关
  6. /// </summary>
  7. public class EnemyController : MonoBehaviour
  8. {
  9. public float speed = 3;//移动速度
  10. public bool isVertical;//是否垂直方向移动
  11. private Vector2 moveDirection;//移动方向
  12. private Rigidbody2D rbody;//引入刚体变量
  13. // Start is called before the first frame update
  14. void Start()
  15. {
  16. rbody = GetComponent<Rigidbody2D>();
  17. moveDirection = isVertical ? Vector2.up : Vector2.right;//如果垂直移动,方向朝上,否则朝右
  18. }
  19. // Update is called once per frame
  20. void Update()
  21. {
  22. Vector2 position = rbody.position;
  23. position.x += moveDirection.x * speed * Time.deltaTime;
  24. position.y += moveDirection.y * speed * Time.deltaTime;
  25. rbody.MovePosition(position);
  26. }
  27. }

*注意:在引用这个脚本后,Robot脚本得属性栏中有一个可勾选的isVertical,勾选则向上,不勾则向右。

        3、控制敌人移动的脚本2:使敌人改变方向来回巡逻

  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. /// <summary>
  5. /// 敌人控制相关
  6. /// </summary>
  7. public class EnemyController : MonoBehaviour
  8. {
  9. public float speed = 3;//移动速度
  10. public float changeDirectionTime = 2f;//改变方向的时间
  11. private float changeTimer;//改变方向的计时器
  12. public bool isVertical;//是否垂直方向移动
  13. private Vector2 moveDirection;//移动方向
  14. private Rigidbody2D rbody;//引入刚体变量
  15. // Start is called before the first frame update
  16. void Start()
  17. {
  18. rbody = GetComponent<Rigidbody2D>();
  19. moveDirection = isVertical ? Vector2.up : Vector2.right;//如果垂直移动,方向朝上,否则朝右
  20. changeTimer = changeDirectionTime;
  21. }
  22. // Update is called once per frame
  23. void Update()
  24. {
  25. changeTimer -= Time.deltaTime;
  26. if(changeTimer < 0)
  27. {
  28. moveDirection *= -1;
  29. changeTimer = changeDirectionTime;
  30. }
  31. Vector2 position = rbody.position;
  32. position.x += moveDirection.x * speed * Time.deltaTime;
  33. position.y += moveDirection.y * speed * Time.deltaTime;
  34. rbody.MovePosition(position);
  35. }
  36. }

        4、给机器人增加碰撞脚本:

  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. /// <summary>
  5. /// 敌人控制相关
  6. /// </summary>
  7. public class EnemyController : MonoBehaviour
  8. {
  9. public float speed = 3;//移动速度
  10. public float changeDirectionTime = 2f;//改变方向的时间
  11. private float changeTimer;//改变方向的计时器
  12. public bool isVertical;//是否垂直方向移动
  13. private Vector2 moveDirection;//移动方向
  14. private Rigidbody2D rbody;//引入刚体变量
  15. // Start is called before the first frame update
  16. void Start()
  17. {
  18. rbody = GetComponent<Rigidbody2D>();
  19. moveDirection = isVertical ? Vector2.up : Vector2.right;//如果垂直移动,方向朝上,否则朝右
  20. changeTimer = changeDirectionTime;
  21. }
  22. // Update is called once per frame
  23. void Update()
  24. {
  25. changeTimer -= Time.deltaTime;
  26. if(changeTimer < 0)
  27. {
  28. moveDirection *= -1;
  29. changeTimer = changeDirectionTime;
  30. }
  31. Vector2 position = rbody.position;
  32. position.x += moveDirection.x * speed * Time.deltaTime;
  33. position.y += moveDirection.y * speed * Time.deltaTime;
  34. rbody.MovePosition(position);
  35. }
  36. void OnCollisionEnter2D(Collision2D other)
  37. {//这里碰撞使用的函数是OnCollisionEnter因为玩家与敌人都是物理刚体且不需要穿过所以这个碰撞方法比较好
  38. //之前用过的OnTriggerEnter是触发碰撞,玩家碰到物体可触发穿透物体,两种碰撞方法各有其优,请见机选择
  39. PlayerController pc = other.gameObject.GetComponent<PlayerController>();
  40. if(pc!=null)
  41. {
  42. pc.ChangeHealth(-1);
  43. }
  44. }
  45. }

第八步:添加物品动画

(1)目的:使画面更加生动。

(2)方法:

1、选择一个要加动画的物体

2、点击Window->Animation->Animation(或者按快捷键Ctrl+6)

3、制作界面出来后,点击creat->Asset->新建一个文件夹Animator->点击进入再新建一个文件夹Items->点击进入在新建一个文件夹idle

4、建好之后回到制作界面,将帧数调低,Samples:60->4

5、Add Property->Transform->Scale(缩放)

6、调帧

7、点击下方Curves调节曲线使变化更平滑。

8、若调整好的物品是预制体的话,那么直接复制粘贴就可以得到一堆长得一样的会动的物品。

第九步:添加敌人动画

(1)目的:使敌人更具威慑力。

(2)方法:

1、将敌人移动的图片素材上下左一次拉入Robot对象中,然后在Animator中新建Enemy文件夹专门存放敌人动画。然后点击ctrl+6,出现了动画制作界面,因为素材中没有给到向右的动画,所以我们将新建一组动画,然后将向左的动画进行x轴的Flip(翻转),这样就得到了一组向右的动画。

2、如何将向左的动画调制向右:假设你已经将左、上、下的三个动画制作完成(1)、在制作动画界面点击creat new clip,命名robot_right(与其他三组保持一致即可),(2)、将下方素材向左的图片选择并拉入制作动画界面的右半部分,然后调好帧数,点击add property,选择Spirit Renderder

选择Filp X(水平翻转)加入,然后就挨帧打钩就行了。

3、点击robot属性栏,找到Animator,点击Controller,查看动画树

4、将左侧robot拖拽如右下预览窗中即可预览动画结果。

5、点击右键创建混合树(右键->Creat State->From New Blend Tree)

6、单击新建的Blend Tree模块,将右侧的属性名称改成Walk,再双击Walk模块再单击Blend Tree模块,右侧属性栏里,找到Blend Type选项选择 Simple Derictional 2D选项。在属性栏找到List is Empty点击+号,选择motion is filed。然后再点击下方加号加到四个为止。然后在自己创建的Enemy动画文件夹中选择四个动画依次放入刚创建的动画框中。

调节参数。返回,右键walk将他设为默认枝干,并把多余的模块删掉。

7、给混合树两个参数,现将默认参数改名为moveX

点击小菜单栏paramenters,再点击加号,Trigger一个新的触发器,命名为fix用来显示修好的动画

8、点击路径箭头,在右侧属性栏找到BlendTree点击加号,将选项调成fix,上方的has exit time取消勾选,Setting里面的Fixed Duration取消勾选,下方的Transition Duration清零即可。

9、左侧小菜单栏点加号float,新建moveY,在双击walk,点击动画主模块,在右侧属性栏Paramaters中一个选择moveX,另一个选择moveY。

10、在脚本里面设置动画

walk动画调参:

 修改动画路径:

第十步:添加玩家动画

(1)目的:使玩家更喜欢游戏角色。

(2)方法:

1、点击角色Ruby文件,右侧属性栏新增组件Animator,找到Controller栏,选项为Ruby,然后Ruby动画就完成了。(这里得感谢官方大大)

2、编写播放角色动画的脚本: 

  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. /// <summary>
  5. /// 控制角色移动、生命、动画等
  6. /// </summary>
  7. public class PlayerController : MonoBehaviour
  8. {
  9. public float speed = 5f;//移动速度
  10. private int maxHealth = 5;//最大生命值
  11. private int currentHealth;//当前生命值
  12. //访问私有变量的两个函数
  13. public int MyMaxHealth { get { return maxHealth; } }
  14. public int MyCurrentHealth { get { return currentHealth; } }
  15. private float invincibleTime = 2f;//无敌时间两秒
  16. private float invicibleTimer;//无敌计时器
  17. private bool isInvincible;//是否处于无敌状态
  18. //=======玩家朝向====================================
  19. private Vector2 lookDirection = new Vector2(1, 0);//玩家默认朝向右
  20. Rigidbody2D rbody;//刚体组件
  21. Animator anim;
  22. // Start is called before the first frame update
  23. void Start()
  24. {
  25. currentHealth = 2;//设置初始血量为2
  26. invicibleTimer = 0;
  27. rbody = GetComponent<Rigidbody2D>();
  28. anim = GetComponent<Animator>();
  29. }
  30. // Update is called once per frame
  31. void Update()
  32. {
  33. float moveX = Input.GetAxisRaw("Horizontal");//控制水平移动方向 A:-1 D:1 不按: 0
  34. float moveY = Input.GetAxisRaw("Vertical");//控制垂直移动方向 W:-1 S:1 不按: 0
  35. Vector2 moveVector = new Vector2(moveX, moveY);
  36. if(moveVector.x != 0 || moveVector.y != 0)
  37. {
  38. lookDirection = moveVector;
  39. }
  40. anim.SetFloat("Look X", lookDirection.x);
  41. anim.SetFloat("Look Y", lookDirection.y);
  42. anim.SetFloat("Speed", moveVector.magnitude);
  43. //================移动================================================
  44. Vector2 position = rbody.position;//定义角色位置向量
  45. position += moveVector * speed * Time.deltaTime;
  46. rbody.MovePosition(position);//将位置信息传输给角色
  47. //==================无敌计时==============================================
  48. if (isInvincible)
  49. {
  50. invicibleTimer -= Time.deltaTime;
  51. if(invicibleTimer < 0)
  52. {
  53. isInvincible = false;//倒计时结束后取消无敌状态
  54. }
  55. }
  56. }
  57. /// <summary>
  58. /// 改变玩家的生命值
  59. /// </summary>
  60. public void ChangeHealth(int amount)
  61. {
  62. if(amount < 0)
  63. {
  64. if (isInvincible == true)
  65. return;
  66. isInvincible = true;
  67. invicibleTimer = invincibleTime;
  68. }
  69. Debug.Log(currentHealth + "/" + maxHealth);
  70. //把玩家的生命值约束在0到最大值之间
  71. currentHealth = Mathf.Clamp(currentHealth + amount, 0, maxHealth);
  72. Debug.Log(currentHealth + "/" + maxHealth);
  73. }
  74. }

第十一步:发射子弹

(1)目的:使游戏具有打击感。

(2)方法:

1、拖拽子弹图片拉入任务栏,调整好图片尺寸,增加刚体(rigidbody2D),和碰撞属性(collider2D)。

2、编写子弹脚本(BulletController)

  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. /// <summary>
  5. /// 控制子弹的移动、碰撞
  6. /// </summary>
  7. public class BulletController : MonoBehaviour
  8. {
  9. Rigidbody2D rbody;
  10. // Start is called before the first frame update
  11. void Awake()
  12. {
  13. rbody = GetComponent<Rigidbody2D>();
  14. }
  15. // Update is called once per frame
  16. void Update()
  17. {
  18. }
  19. /// <summary>
  20. /// 子弹的移动
  21. /// </summary>
  22. public void Move(Vector2 moveDirection, float moveForce)
  23. {
  24. rbody.AddForce(moveDirection * moveForce);
  25. }
  26. }

*注意:这里没有用Start()方法,而是用的Awake()方法,是因为Start方法不会在程序运行就执行,所以刚体组件不会立刻就被调用。如用了Awake方法的话,里面的语句是程序一开始就可以执行的。

3、与子弹相关的玩家脚本:

  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. /// <summary>
  5. /// 控制角色移动、生命、动画等
  6. /// </summary>
  7. public class PlayerController : MonoBehaviour
  8. {
  9. public float speed = 5f;//移动速度
  10. private int maxHealth = 5;//最大生命值
  11. private int currentHealth;//当前生命值
  12. //访问私有变量的两个函数
  13. public int MyMaxHealth { get { return maxHealth; } }
  14. public int MyCurrentHealth { get { return currentHealth; } }
  15. private float invincibleTime = 2f;//无敌时间两秒
  16. private float invicibleTimer;//无敌计时器
  17. private bool isInvincible;//是否处于无敌状态
  18. public GameObject bulletPrefab;//子弹
  19. //=======玩家朝向====================================
  20. private Vector2 lookDirection = new Vector2(1, 0);//玩家默认朝向右
  21. Rigidbody2D rbody;//刚体组件
  22. Animator anim;
  23. // Start is called before the first frame update
  24. void Start()
  25. {
  26. currentHealth = 2;//设置初始血量为2
  27. invicibleTimer = 0;
  28. rbody = GetComponent<Rigidbody2D>();
  29. anim = GetComponent<Animator>();
  30. }
  31. // Update is called once per frame
  32. void Update()
  33. {
  34. float moveX = Input.GetAxisRaw("Horizontal");//控制水平移动方向 A:-1 D:1 不按: 0
  35. float moveY = Input.GetAxisRaw("Vertical");//控制垂直移动方向 W:-1 S:1 不按: 0
  36. Vector2 moveVector = new Vector2(moveX, moveY);
  37. if(moveVector.x != 0 || moveVector.y != 0)
  38. {
  39. lookDirection = moveVector;
  40. }
  41. anim.SetFloat("Look X", lookDirection.x);
  42. anim.SetFloat("Look Y", lookDirection.y);
  43. anim.SetFloat("Speed", moveVector.magnitude);
  44. //================移动================================================
  45. Vector2 position = rbody.position;//定义角色位置向量
  46. position += moveVector * speed * Time.deltaTime;
  47. rbody.MovePosition(position);//将位置信息传输给角色
  48. //==================无敌计时==============================================
  49. if (isInvincible)
  50. {
  51. invicibleTimer -= Time.deltaTime;
  52. if(invicibleTimer < 0)
  53. {
  54. isInvincible = false;//倒计时结束后取消无敌状态
  55. }
  56. }
  57. //==========按下 J 键,进行攻击================================
  58. if(Input.GetKeyDown(KeyCode.J))
  59. {
  60. GameObject bullet = Instantiate(bulletPrefab, rbody.position, Quaternion.identity);
  61. BulletController bc = bullet.GetComponent<BulletController>();
  62. if(bc != null)
  63. {
  64. bc.Move(lookDirection, 300);
  65. }
  66. }
  67. }
  68. /// <summary>
  69. /// 改变玩家的生命值
  70. /// </summary>
  71. public void ChangeHealth(int amount)
  72. {
  73. if(amount < 0)
  74. {
  75. if (isInvincible == true)
  76. return;
  77. isInvincible = true;
  78. invicibleTimer = invincibleTime;
  79. }
  80. Debug.Log(currentHealth + "/" + maxHealth);
  81. //把玩家的生命值约束在0到最大值之间
  82. currentHealth = Mathf.Clamp(currentHealth + amount, 0, maxHealth);
  83. Debug.Log(currentHealth + "/" + maxHealth);
  84. }
  85. }

*注意:脚本写好之后,将脚本挂在子弹上,然后将子弹做成预制体,将原来的任务栏中的子弹删除。打开预制体文件夹找到子弹预制体,在点击左侧玩家对象将预制体的拖入到右侧玩家属性栏中player Controller (script)中的bullet prefab里面就行了。

完成之后按下 J 建就能发射子弹了,如果子弹发生旋转请在刚体属性中勾选freeze Z。

在发射子弹的过程中,子弹与玩家会产生刚体与刚体间的碰撞,怎么解除这种碰撞呢,请看下文。

4、解除子弹与玩家间的碰撞

        1、点击玩家,查看属性,点击选择新增,选择第八层创建player(随便选),选择第九层创建bullet。

        2、保存。将玩家和子弹的Layer改成player和bullet

        3、点击上方菜单栏Edit->Project Settings->Pysics 2D,右下方就是碰撞矩阵,将玩家和bullet的勾选取消,它们就不会发生碰撞了,再把bullet和bullet的勾选取消即可。

        4、改写子弹脚本:使子弹碰到物体后消失。

  1. //碰撞检测
  2. void OnCollisionEnter2D(Collision2D other)
  3. {
  4. Destroy(this.gameObject);
  5. }

        5、两秒以后消失

  1. void Awake()
  2. {
  3. rbody = GetComponent<Rigidbody2D>();
  4. Destroy(this.gameObject, 2f);//两秒后消失
  5. }

        6设置子弹与敌人的碰撞

  1. //碰撞检测
  2. void OnCollisionEnter2D(Collision2D other)
  3. {
  4. EnemyController ec = other.gameObject.GetComponent<EnemyController>();
  5. if(ec != null)
  6. {
  7. Debug.Log("碰到敌人了");
  8. }
  9. Destroy(this.gameObject);
  10. }

        7、播放敌人修复动画:

  1. /// <summary>
  2. /// 敌人修复
  3. /// </summary>
  4. public void Fixed()
  5. {
  6. rbody.simulated = false;
  7. anim.SetTrigger("fix");
  8. }

     机器人已修复:

   8、机器人被修理的脚本

  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. /// <summary>
  5. /// 敌人控制相关
  6. /// </summary>
  7. public class EnemyController : MonoBehaviour
  8. {
  9. public float speed = 3;//移动速度
  10. public float changeDirectionTime = 2f;//改变方向的时间
  11. private float changeTimer;//改变方向的计时器
  12. public bool isVertical;//是否垂直方向移动
  13. private Vector2 moveDirection;//移动方向
  14. private Rigidbody2D rbody;//引入刚体变量
  15. private bool isFixed;//是否被修复
  16. private Animator anim;//获取动画组件
  17. // Start is called before the first frame update
  18. void Start()
  19. {
  20. rbody = GetComponent<Rigidbody2D>();
  21. anim = GetComponent<Animator>();//创建动画组件对象
  22. moveDirection = isVertical ? Vector2.up : Vector2.right;//如果垂直移动,方向朝上,否则朝右
  23. changeTimer = changeDirectionTime;
  24. isFixed = false;
  25. }
  26. // Update is called once per frame
  27. void Update()
  28. {
  29. if (isFixed) return;//被修理了就停止以下活动
  30. changeTimer -= Time.deltaTime;
  31. if(changeTimer < 0)
  32. {
  33. moveDirection *= -1;
  34. changeTimer = changeDirectionTime;
  35. }
  36. Vector2 position = rbody.position;
  37. position.x += moveDirection.x * speed * Time.deltaTime;
  38. position.y += moveDirection.y * speed * Time.deltaTime;
  39. rbody.MovePosition(position);
  40. anim.SetFloat("moveX", moveDirection.x);
  41. anim.SetFloat("moveY", moveDirection.y);
  42. }
  43. /// <summary>
  44. /// 与玩家的碰撞检测
  45. /// </summary>
  46. /// <param name="other"></param>
  47. void OnCollisionEnter2D(Collision2D other)
  48. {//这里碰撞使用的函数是OnCollisionEnter因为玩家与敌人都是物理刚体且不需要穿过所以这个碰撞方法比较好
  49. //之前用过的OnTriggerEnter是触发碰撞,玩家碰到物体可触发穿透物体,两种碰撞方法各有其优,请见机选择
  50. PlayerController pc = other.gameObject.GetComponent<PlayerController>();
  51. if(pc!=null)
  52. {
  53. pc.ChangeHealth(-1);
  54. }
  55. }
  56. /// <summary>
  57. /// 敌人修复
  58. /// </summary>
  59. public void Fixed()
  60. {
  61. isFixed = true;
  62. rbody.simulated = false;
  63. anim.SetTrigger("fix");
  64. }
  65. }

        *注意:写好之后不要忘记在子弹类中调用

  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. /// <summary>
  5. /// 控制子弹的移动、碰撞
  6. /// </summary>
  7. public class BulletController : MonoBehaviour
  8. {
  9. Rigidbody2D rbody;
  10. // Start is called before the first frame update
  11. void Awake()
  12. {
  13. rbody = GetComponent<Rigidbody2D>();
  14. Destroy(this.gameObject, 2f);//两秒后消失
  15. }
  16. // Update is called once per frame
  17. void Update()
  18. {
  19. }
  20. /// <summary>
  21. /// 子弹的移动
  22. /// </summary>
  23. public void Move(Vector2 moveDirection, float moveForce)
  24. {
  25. rbody.AddForce(moveDirection * moveForce);
  26. }
  27. //碰撞检测
  28. void OnCollisionEnter2D(Collision2D other)
  29. {
  30. EnemyController ec = other.gameObject.GetComponent<EnemyController>();
  31. if(ec != null)
  32. {
  33. ec.Fixed();//修复敌人
  34. }
  35. Destroy(this.gameObject);
  36. }
  37. }

        9、子弹发射位置微调(本来是在脚底现在调到中央)

  1. //==========按下 J 键,进行攻击================================
  2. if(Input.GetKeyDown(KeyCode.J))
  3. {
  4. anim.SetTrigger("Launch");//播放攻击动画
  5. GameObject bullet = Instantiate(bulletPrefab, rbody.position + Vector2.up * 0.5f, Quaternion.identity);
  6. BulletController bc = bullet.GetComponent<BulletController>();
  7. if(bc != null)
  8. {
  9. bc.Move(lookDirection, 300);
  10. }
  11. }

第十二步:增加敌人特效

(1)目的:使游戏画面更真实。

(2)方法:

1、找到特效素材

2、将素材Spirit Mode改成multiple

3、点击Spirit Edit

4、点击slience,再点按数量切割,选择C :4  R : 4,就切好了。

5、任务栏右键Effects->Partical System,重命名brokenEffect

6、特效属性栏中找到贴图T..S..A勾选上,Mode改成Spirit,加入两张特效图片。

7、点击frame,点击小三角,选择随机,参数改成 0-2就可随机播放两张图了

8、在Asset文件夹下新建文件夹Materials,进入右键creat->material新建一个采色球叫effectMaterial。

9、查看属性,Sharder选择Particles 选择 Alpha Blended,随便选张图片(子弹带)

10、回到特效属性,查看Renderer,将material选择刚刚创建的采色球,这样边框就没了

11、再调属性:

        生存周期、生成速度、初始大小、初始旋转、所在space调成world、stop action调成destroy,跟随游戏体共存亡。在点击shape调整形状。*调渐变色:color over lifetime,调上面的针能控制透明度。

       ***注意: 如何去掉特效的橙色边框:在scenes视窗里有个gizmos菜单,打开后有一个selection outline选项,把它前面的勾选去掉就好了

        ***注意:如果你所做成的特效被场景遮挡,不要慌,这是图层测次序问题,找到特效属性栏中的Renderer,找到order of Layer,将此处的数值改成比图层数值大的即可。

12、修补后特效消失脚本(敌人类)

  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. /// <summary>
  5. /// 敌人控制相关
  6. /// </summary>
  7. public class EnemyController : MonoBehaviour
  8. {
  9. public float speed = 3;//移动速度
  10. public float changeDirectionTime = 2f;//改变方向的时间
  11. private float changeTimer;//改变方向的计时器
  12. public bool isVertical;//是否垂直方向移动
  13. private Vector2 moveDirection;//移动方向
  14. public ParticleSystem brokenEffect;//损坏特效
  15. private Rigidbody2D rbody;//引入刚体变量
  16. private bool isFixed;//是否被修复
  17. private Animator anim;//获取动画组件
  18. // Start is called before the first frame update
  19. void Start()
  20. {
  21. rbody = GetComponent<Rigidbody2D>();
  22. anim = GetComponent<Animator>();//创建动画组件对象
  23. moveDirection = isVertical ? Vector2.up : Vector2.right;//如果垂直移动,方向朝上,否则朝右
  24. changeTimer = changeDirectionTime;
  25. isFixed = false;
  26. }
  27. // Update is called once per frame
  28. void Update()
  29. {
  30. if (isFixed) return;//被修理了就停止以下活动
  31. changeTimer -= Time.deltaTime;
  32. if(changeTimer < 0)
  33. {
  34. moveDirection *= -1;
  35. changeTimer = changeDirectionTime;
  36. }
  37. Vector2 position = rbody.position;
  38. position.x += moveDirection.x * speed * Time.deltaTime;
  39. position.y += moveDirection.y * speed * Time.deltaTime;
  40. rbody.MovePosition(position);
  41. anim.SetFloat("moveX", moveDirection.x);
  42. anim.SetFloat("moveY", moveDirection.y);
  43. }
  44. /// <summary>
  45. /// 与玩家的碰撞检测
  46. /// </summary>
  47. /// <param name="other"></param>
  48. void OnCollisionEnter2D(Collision2D other)
  49. {//这里碰撞使用的函数是OnCollisionEnter因为玩家与敌人都是物理刚体且不需要穿过所以这个碰撞方法比较好
  50. //之前用过的OnTriggerEnter是触发碰撞,玩家碰到物体可触发穿透物体,两种碰撞方法各有其优,请见机选择
  51. PlayerController pc = other.gameObject.GetComponent<PlayerController>();
  52. if(pc!=null)
  53. {
  54. pc.ChangeHealth(-1);
  55. }
  56. }
  57. /// <summary>
  58. /// 敌人修复
  59. /// </summary>
  60. public void Fixed()
  61. {
  62. isFixed = true;
  63. if(brokenEffect.isPlaying == true)
  64. {
  65. brokenEffect.Stop();
  66. }
  67. rbody.simulated = false;
  68. anim.SetTrigger("fix");
  69. }
  70. }

*注意:编写完这个脚本后,要机器人目录下的特效拖入右侧的属性栏的 BrokenEffect 里,否则程序无法正常执行。

第十三步:增添物品特效 

(1)目的(同上)

(2)方法(仿上)

第十三步:血条显示

(1)目的:使玩家直观的感受到角色的状态。

(2)方法:

1、任务列表右键UI->image->自动生成Canvas画布->image重命名HeadFrame->右侧属性栏Source Image选择想要的图片,点击set native size恢复原始大小,按住shift可以进行等比例缩放。在属性栏中点击排布图标,按住alt键选择排版。点击Game窗口可以预览效果。

2、 调整headframe框的缩放大小,点击Canvas点击属性scale with screem size(随着屏幕窗口大小改变)

3、 在HeadImage文件下在新增一个图片文件叫head同样的方法将头像放在头像框上,然后再创建一个HealthBar图片文件,将血条图片加载进来。然后将血条的长短用数值控制。(1)点击血条文件,将image type选择filled,将fill mothod改成Hrizonal,即可。

4、新建脚本血量可视化:(新建UImanager类)

  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using UnityEngine.UI;
  5. /// <summary>
  6. /// UI管理相关
  7. /// </summary>
  8. public class UImanager : MonoBehaviour
  9. {
  10. //单例模式
  11. public static UImanager instance { get; private set; }
  12. void Awake()
  13. {
  14. instance = this;
  15. }
  16. public Image healthBar;
  17. /// <summary>
  18. /// 更新血条
  19. /// </summary>
  20. public void UpdateHealthBar(int curAmount, int maxAmount)
  21. {
  22. healthBar.fillAmount = (float)curAmount / (float)maxAmount;
  23. }
  24. }

5、角色脚本相关:

  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. /// <summary>
  5. /// 控制角色移动、生命、动画等
  6. /// </summary>
  7. public class PlayerController : MonoBehaviour
  8. {
  9. public float speed = 5f;//移动速度
  10. private int maxHealth = 5;//最大生命值
  11. private int currentHealth;//当前生命值
  12. //访问私有变量的两个函数
  13. public int MyMaxHealth { get { return maxHealth; } }
  14. public int MyCurrentHealth { get { return currentHealth; } }
  15. private float invincibleTime = 2f;//无敌时间两秒
  16. private float invicibleTimer;//无敌计时器
  17. private bool isInvincible;//是否处于无敌状态
  18. public GameObject bulletPrefab;//子弹
  19. //=======玩家朝向====================================
  20. private Vector2 lookDirection = new Vector2(1, 0);//玩家默认朝向右
  21. Rigidbody2D rbody;//刚体组件
  22. Animator anim;
  23. // Start is called before the first frame update
  24. void Start()
  25. {
  26. currentHealth = 5;//设置初始血量为2
  27. invicibleTimer = 0;
  28. rbody = GetComponent<Rigidbody2D>();
  29. anim = GetComponent<Animator>();
  30. }
  31. // Update is called once per frame
  32. void Update()
  33. {
  34. float moveX = Input.GetAxisRaw("Horizontal");//控制水平移动方向 A:-1 D:1 不按: 0
  35. float moveY = Input.GetAxisRaw("Vertical");//控制垂直移动方向 W:-1 S:1 不按: 0
  36. Vector2 moveVector = new Vector2(moveX, moveY);
  37. if(moveVector.x != 0 || moveVector.y != 0)
  38. {
  39. lookDirection = moveVector;
  40. }
  41. anim.SetFloat("Look X", lookDirection.x);
  42. anim.SetFloat("Look Y", lookDirection.y);
  43. anim.SetFloat("Speed", moveVector.magnitude);
  44. //================移动================================================
  45. Vector2 position = rbody.position;//定义角色位置向量
  46. position += moveVector * speed * Time.deltaTime;
  47. rbody.MovePosition(position);//将位置信息传输给角色
  48. //==================无敌计时==============================================
  49. if (isInvincible)
  50. {
  51. invicibleTimer -= Time.deltaTime;
  52. if(invicibleTimer < 0)
  53. {
  54. isInvincible = false;//倒计时结束后取消无敌状态
  55. }
  56. }
  57. //==========按下 J 键,进行攻击================================
  58. if(Input.GetKeyDown(KeyCode.J))
  59. {
  60. anim.SetTrigger("Launch");//播放攻击动画
  61. GameObject bullet = Instantiate(bulletPrefab, rbody.position + Vector2.up * 0.5f, Quaternion.identity);
  62. BulletController bc = bullet.GetComponent<BulletController>();
  63. if(bc != null)
  64. {
  65. bc.Move(lookDirection, 300);
  66. }
  67. }
  68. }
  69. /// <summary>
  70. /// 改变玩家的生命值
  71. /// </summary>
  72. public void ChangeHealth(int amount)
  73. {
  74. if(amount < 0)
  75. {
  76. if (isInvincible == true)
  77. return;
  78. isInvincible = true;
  79. invicibleTimer = invincibleTime;
  80. }
  81. Debug.Log(currentHealth + "/" + maxHealth);
  82. //把玩家的生命值约束在0到最大值之间
  83. currentHealth = Mathf.Clamp(currentHealth + amount, 0, maxHealth);
  84. UImanager.instance.UpdateHealthBar(currentHealth, maxHealth);
  85. Debug.Log(currentHealth + "/" + maxHealth);
  86. }
  87. }

*注意:写完脚本需要给脚本一个对象,现在左侧任务栏中新建一个空文件取名为UImanager,然后将UImanager脚本挂在上面,在把healthBar的UI拖拽进UImanager属性栏中。

第十五步:增加场景音乐

(1)目的:增强游戏沉浸感。

(2)方法:

1、新建文件夹AudioManager->添加组件AudioSource->AudioClip选择背景音乐设置循环播放

2、新建脚本:AudioManager

  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. /// <summary>
  5. /// 播放音乐音效
  6. /// </summary>
  7. public class AudioManager : MonoBehaviour
  8. {
  9. public static AudioManager instance { get; private set; }
  10. private AudioSource audioS;
  11. // Start is called before the first frame update
  12. void Start()
  13. {
  14. instance = this;
  15. audioS = GetComponent<AudioSource>();
  16. }
  17. /// <summary>
  18. /// 播放特定音效
  19. /// </summary>
  20. /// <param name="clip"></param>
  21. public void AudioPlay(AudioClip clip)
  22. {
  23. audioS.PlayOneShot(clip);
  24. }
  25. }

3、角色加音效

  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. /// <summary>
  5. /// 控制角色移动、生命、动画等
  6. /// </summary>
  7. public class PlayerController : MonoBehaviour
  8. {
  9. public float speed = 5f;//移动速度
  10. private int maxHealth = 5;//最大生命值
  11. private int currentHealth;//当前生命值
  12. //访问私有变量的两个函数
  13. public int MyMaxHealth { get { return maxHealth; } }
  14. public int MyCurrentHealth { get { return currentHealth; } }
  15. private float invincibleTime = 2f;//无敌时间两秒
  16. private float invicibleTimer;//无敌计时器
  17. private bool isInvincible;//是否处于无敌状态
  18. public GameObject bulletPrefab;//子弹
  19. //=================玩家的音效=====================
  20. public AudioClip hitClip;//受伤音效
  21. public AudioClip lauchClip;//发射音效
  22. //=======玩家朝向====================================
  23. private Vector2 lookDirection = new Vector2(1, 0);//玩家默认朝向右
  24. Rigidbody2D rbody;//刚体组件
  25. Animator anim;
  26. // Start is called before the first frame update
  27. void Start()
  28. {
  29. currentHealth = 5;//设置初始血量为2
  30. invicibleTimer = 0;
  31. rbody = GetComponent<Rigidbody2D>();
  32. anim = GetComponent<Animator>();
  33. }
  34. // Update is called once per frame
  35. void Update()
  36. {
  37. float moveX = Input.GetAxisRaw("Horizontal");//控制水平移动方向 A:-1 D:1 不按: 0
  38. float moveY = Input.GetAxisRaw("Vertical");//控制垂直移动方向 W:-1 S:1 不按: 0
  39. Vector2 moveVector = new Vector2(moveX, moveY);
  40. if(moveVector.x != 0 || moveVector.y != 0)
  41. {
  42. lookDirection = moveVector;
  43. }
  44. anim.SetFloat("Look X", lookDirection.x);
  45. anim.SetFloat("Look Y", lookDirection.y);
  46. anim.SetFloat("Speed", moveVector.magnitude);
  47. //================移动================================================
  48. Vector2 position = rbody.position;//定义角色位置向量
  49. position += moveVector * speed * Time.deltaTime;
  50. rbody.MovePosition(position);//将位置信息传输给角色
  51. //==================无敌计时==============================================
  52. if (isInvincible)
  53. {
  54. invicibleTimer -= Time.deltaTime;
  55. if(invicibleTimer < 0)
  56. {
  57. isInvincible = false;//倒计时结束后取消无敌状态
  58. }
  59. }
  60. //==========按下 J 键,进行攻击================================
  61. if(Input.GetKeyDown(KeyCode.J))
  62. {
  63. anim.SetTrigger("Launch");//播放攻击动画
  64. AudioManager.instance.AudioPlay(lauchClip);//攻击音效
  65. GameObject bullet = Instantiate(bulletPrefab, rbody.position + Vector2.up * 0.5f, Quaternion.identity);
  66. BulletController bc = bullet.GetComponent<BulletController>();
  67. if(bc != null)
  68. {
  69. bc.Move(lookDirection, 300);
  70. }
  71. }
  72. }
  73. /// <summary>
  74. /// 改变玩家的生命值
  75. /// </summary>
  76. public void ChangeHealth(int amount)
  77. {
  78. if(amount < 0)
  79. {
  80. if (isInvincible == true)
  81. return;
  82. isInvincible = true;
  83. anim.SetTrigger("Hit");
  84. AudioManager.instance.AudioPlay(hitClip);//受伤音效
  85. invicibleTimer = invincibleTime;
  86. }
  87. Debug.Log(currentHealth + "/" + maxHealth);
  88. //把玩家的生命值约束在0到最大值之间
  89. currentHealth = Mathf.Clamp(currentHealth + amount, 0, maxHealth);
  90. UImanager.instance.UpdateHealthBar(currentHealth, maxHealth);
  91. Debug.Log(currentHealth + "/" + maxHealth);
  92. }
  93. }

4、敌人加音效

  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. /// <summary>
  5. /// 敌人控制相关
  6. /// </summary>
  7. public class EnemyController : MonoBehaviour
  8. {
  9. public float speed = 3;//移动速度
  10. public float changeDirectionTime = 2f;//改变方向的时间
  11. private float changeTimer;//改变方向的计时器
  12. public bool isVertical;//是否垂直方向移动
  13. private Vector2 moveDirection;//移动方向
  14. public ParticleSystem brokenEffect;//损坏特效
  15. public AudioClip fixedClip;//被修复的音效
  16. private Rigidbody2D rbody;//引入刚体变量
  17. private bool isFixed;//是否被修复
  18. private Animator anim;//获取动画组件
  19. // Start is called before the first frame update
  20. void Start()
  21. {
  22. rbody = GetComponent<Rigidbody2D>();
  23. anim = GetComponent<Animator>();//创建动画组件对象
  24. moveDirection = isVertical ? Vector2.up : Vector2.right;//如果垂直移动,方向朝上,否则朝右
  25. changeTimer = changeDirectionTime;
  26. isFixed = false;
  27. }
  28. // Update is called once per frame
  29. void Update()
  30. {
  31. if (isFixed) return;//被修理了就停止以下活动
  32. changeTimer -= Time.deltaTime;
  33. if(changeTimer < 0)
  34. {
  35. moveDirection *= -1;
  36. changeTimer = changeDirectionTime;
  37. }
  38. Vector2 position = rbody.position;
  39. position.x += moveDirection.x * speed * Time.deltaTime;
  40. position.y += moveDirection.y * speed * Time.deltaTime;
  41. rbody.MovePosition(position);
  42. anim.SetFloat("moveX", moveDirection.x);
  43. anim.SetFloat("moveY", moveDirection.y);
  44. }
  45. /// <summary>
  46. /// 与玩家的碰撞检测
  47. /// </summary>
  48. /// <param name="other"></param>
  49. void OnCollisionEnter2D(Collision2D other)
  50. {//这里碰撞使用的函数是OnCollisionEnter因为玩家与敌人都是物理刚体且不需要穿过所以这个碰撞方法比较好
  51. //之前用过的OnTriggerEnter是触发碰撞,玩家碰到物体可触发穿透物体,两种碰撞方法各有其优,请见机选择
  52. PlayerController pc = other.gameObject.GetComponent<PlayerController>();
  53. if(pc!=null)
  54. {
  55. pc.ChangeHealth(-1);
  56. }
  57. }
  58. /// <summary>
  59. /// 敌人修复
  60. /// </summary>
  61. public void Fixed()
  62. {
  63. isFixed = true;
  64. if(brokenEffect.isPlaying == true)
  65. {
  66. brokenEffect.Stop();
  67. }
  68. AudioManager.instance.AudioPlay(fixedClip);
  69. rbody.simulated = false;
  70. anim.SetTrigger("fix");
  71. }
  72. }

5射击物加音效

  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. /// <summary>
  5. /// 控制子弹的移动、碰撞
  6. /// </summary>
  7. public class BulletController : MonoBehaviour
  8. {
  9. Rigidbody2D rbody;
  10. public AudioClip hitClip;//命中音效
  11. // Start is called before the first frame update
  12. void Awake()
  13. {
  14. rbody = GetComponent<Rigidbody2D>();
  15. Destroy(this.gameObject, 2f);//两秒后消失
  16. }
  17. // Update is called once per frame
  18. void Update()
  19. {
  20. }
  21. /// <summary>
  22. /// 子弹的移动
  23. /// </summary>
  24. public void Move(Vector2 moveDirection, float moveForce)
  25. {
  26. rbody.AddForce(moveDirection * moveForce);
  27. }
  28. //碰撞检测
  29. void OnCollisionEnter2D(Collision2D other)
  30. {
  31. EnemyController ec = other.gameObject.GetComponent<EnemyController>();
  32. if(ec != null)
  33. {
  34. ec.Fixed();//修复敌人
  35. }
  36. AudioManager.instance.AudioPlay(hitClip);//播放命中音效
  37. Destroy(this.gameObject);
  38. }
  39. }

将音效素材拖入对象属性的相应位置即可。


第十六步:创建NPC

(1)目的:略

(2)方法:

1、找到NPC素材,打包成动画

2、添加对话框->新建画布->UI->Image->建立对话框并调整大小,添加文字

3、写代码:

UImanager脚本:

  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using UnityEngine.UI;
  5. /// <summary>
  6. /// UI管理相关
  7. /// </summary>
  8. public class UImanager : MonoBehaviour
  9. {
  10. //单例模式
  11. public static UImanager instance { get; private set; }
  12. void Awake()
  13. {
  14. instance = this;
  15. }
  16. public Image healthBar;
  17. /// <summary>
  18. /// 更新血条
  19. /// </summary>
  20. public void UpdateHealthBar(int curAmount, int maxAmount)
  21. {
  22. healthBar.fillAmount = (float)curAmount / (float)maxAmount;
  23. }
  24. }

4、NPC对话出现脚本:

  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using UnityEngine.UI;
  5. /// <summary>
  6. /// npc交互
  7. /// </summary>
  8. public class NPCmanager : MonoBehaviour
  9. {
  10. public GameObject tipImage;//提示
  11. public GameObject dialogImage;
  12. public float showTime = 4;//对话显示时间
  13. private float showTimer;//计时器
  14. // Start is called before the first frame update
  15. void Start()
  16. {
  17. tipImage.SetActive(true);
  18. dialogImage.SetActive(false);//初始隐藏对话框
  19. showTimer = -1;
  20. }
  21. void Update()
  22. {
  23. showTimer -= Time.deltaTime;
  24. if(showTimer < 0)
  25. {
  26. tipImage.SetActive(true);
  27. dialogImage.SetActive(false);
  28. }
  29. }
  30. //显示对话框
  31. public void ShowDialog()
  32. {
  33. showTimer = showTime;
  34. tipImage.SetActive(false);
  35. dialogImage.SetActive(true);
  36. }
  37. }

第十七步:创建子弹补给

(1)目的:增加子弹数量。增添游戏趣味性。

(2)方法:

1、与草莓道理相近,先在画面中建立子弹包,然后和角色建立关联脚本

  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. /// <summary>
  5. /// 子弹补给
  6. /// </summary>
  7. public class BulletBag : MonoBehaviour
  8. {
  9. public int bulletCount = 10;//里面含有的子弹数量
  10. void OnTriggerEnter2D(Collider2D other)
  11. {
  12. PlayerController pc = other.GetComponent<PlayerController>();
  13. if(pc!=null)
  14. {
  15. if(pc.MyCurBulletCount < pc.MyMaxBulletCount)
  16. {
  17. pc.ChangeBulletCount(bulletCount);//增加子弹数
  18. Destroy(this.gameObject);
  19. }
  20. }
  21. }
  22. }

2、角色脚本更改

  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. /// <summary>
  5. /// 控制角色移动、生命、动画等
  6. /// </summary>
  7. public class PlayerController : MonoBehaviour
  8. {
  9. public float speed = 5f;//移动速度
  10. private int maxHealth = 5;//最大生命值
  11. private int currentHealth;//当前生命值
  12. //访问私有变量的两个函数
  13. public int MyMaxHealth { get { return maxHealth; } }
  14. public int MyCurrentHealth { get { return currentHealth; } }
  15. private float invincibleTime = 2f;//无敌时间两秒
  16. private float invicibleTimer;//无敌计时器
  17. private bool isInvincible;//是否处于无敌状态
  18. public GameObject bulletPrefab;//子弹
  19. //=================玩家的音效=====================
  20. public AudioClip hitClip;//受伤音效
  21. public AudioClip lauchClip;//发射音效
  22. //=======玩家朝向====================================
  23. private Vector2 lookDirection = new Vector2(1, 0);//玩家默认朝向右
  24. //=====玩家子弹数量========================
  25. [SerializeField]
  26. private int maxBulletCount = 30;
  27. private int curBulletCount;//当前子弹数
  28. public int MyCurBulletCount { get { return curBulletCount; } }
  29. public int MyMaxBulletCount { get { return maxBulletCount; } }
  30. Rigidbody2D rbody;//刚体组件
  31. Animator anim;
  32. // Start is called before the first frame update
  33. void Start()
  34. {
  35. currentHealth = 5;//设置初始血量为2
  36. curBulletCount = 2;
  37. invicibleTimer = 0;
  38. rbody = GetComponent<Rigidbody2D>();
  39. anim = GetComponent<Animator>();
  40. UImanager.instance.UpdateBulletCount(curBulletCount, maxBulletCount);
  41. }
  42. // Update is called once per frame
  43. void Update()
  44. {
  45. float moveX = Input.GetAxisRaw("Horizontal");//控制水平移动方向 A:-1 D:1 不按: 0
  46. float moveY = Input.GetAxisRaw("Vertical");//控制垂直移动方向 W:-1 S:1 不按: 0
  47. Vector2 moveVector = new Vector2(moveX, moveY);
  48. if(moveVector.x != 0 || moveVector.y != 0)
  49. {
  50. lookDirection = moveVector;
  51. }
  52. anim.SetFloat("Look X", lookDirection.x);
  53. anim.SetFloat("Look Y", lookDirection.y);
  54. anim.SetFloat("Speed", moveVector.magnitude);
  55. //================移动================================================
  56. Vector2 position = rbody.position;//定义角色位置向量
  57. position += moveVector * speed * Time.deltaTime;
  58. rbody.MovePosition(position);//将位置信息传输给角色
  59. //==================无敌计时==============================================
  60. if (isInvincible)
  61. {
  62. invicibleTimer -= Time.deltaTime;
  63. if(invicibleTimer < 0)
  64. {
  65. isInvincible = false;//倒计时结束后取消无敌状态
  66. }
  67. }
  68. //==========按下 J 键,进行攻击================================
  69. if(Input.GetKeyDown(KeyCode.J) && curBulletCount > 0)
  70. {
  71. ChangeBulletCount(-1);
  72. anim.SetTrigger("Launch");//播放攻击动画
  73. AudioManager.instance.AudioPlay(lauchClip);//攻击音效
  74. GameObject bullet = Instantiate(bulletPrefab, rbody.position + Vector2.up * 0.5f, Quaternion.identity);
  75. BulletController bc = bullet.GetComponent<BulletController>();
  76. if(bc != null)
  77. {
  78. bc.Move(lookDirection, 300);
  79. }
  80. }
  81. //========按下E键进行对话==================================
  82. if (Input.GetKeyDown(KeyCode.E))
  83. {
  84. RaycastHit2D hit = Physics2D.Raycast(rbody.position, lookDirection, 2f, LayerMask.GetMask("NPC"));
  85. if(hit.collider != null)
  86. {
  87. NPCmanager npc = hit.collider.GetComponent<NPCmanager>();
  88. if(npc != null)
  89. {
  90. npc.ShowDialog();//显示对话框
  91. }
  92. }
  93. }
  94. }
  95. /// <summary>
  96. /// 改变玩家的生命值
  97. /// </summary>
  98. public void ChangeHealth(int amount)
  99. {
  100. if(amount < 0)
  101. {
  102. if (isInvincible == true)
  103. return;
  104. isInvincible = true;
  105. anim.SetTrigger("Hit");
  106. AudioManager.instance.AudioPlay(hitClip);//受伤音效
  107. invicibleTimer = invincibleTime;
  108. }
  109. Debug.Log(currentHealth + "/" + maxHealth);
  110. //把玩家的生命值约束在0到最大值之间
  111. currentHealth = Mathf.Clamp(currentHealth + amount, 0, maxHealth);
  112. UImanager.instance.UpdateHealthBar(currentHealth, maxHealth);
  113. Debug.Log(currentHealth + "/" + maxHealth);
  114. }
  115. //改变子弹数量
  116. public void ChangeBulletCount(int amount)
  117. {
  118. curBulletCount = Mathf.Clamp(curBulletCount + amount, 0, maxBulletCount);//限制子弹数量范围
  119. UImanager.instance.UpdateBulletCount(curBulletCount, maxBulletCount);
  120. }
  121. }

*注意:如果觉得物体遮挡不够真实,可以设置物体属性的锚点为底部就可以了。

        1、Pivot->Bottom

        2、Spirit Sort Point -> Pivot

第十八步:打包文件

步骤:File->Building Settings->选择 add open scence ->build

(下一次要改进的地方:

1、机器人追着玩家跑,如果玩家躲入草丛则机器人发现不了

2、打中箱子掉落隐藏物品

3、实现2.5D饥荒视角

大家还有什么好的想法,评论区积极留言哦)

网站建设定制开发 软件系统开发定制 定制软件开发 软件开发定制 定制app开发 app开发定制 app开发定制公司 电商商城定制开发 定制小程序开发 定制开发小程序 客户管理系统开发定制 定制网站 定制开发 crm开发定制 开发公司 小程序开发定制 定制软件 收款定制开发 企业网站定制开发 定制化开发 android系统定制开发 定制小程序开发费用 定制设计 专注app软件定制开发 软件开发定制定制 知名网站建设定制 软件定制开发供应商 应用系统定制开发 软件系统定制开发 企业管理系统定制开发 系统定制开发