当前位置:   article > 正文

[Untiy2D好项目分享]一个好手感的2D控制器_github unity 2d源码

github unity 2d源码

学习目标:

今天同样在b站上看到一个转载视频这个Unity角色控制器是使用自定义的物理组件制作的,并包含一些隐藏的平台游戏技巧,让玩家体验到优秀的操作手感。

视频地址:

【Unity】好手感从何而来?一款免费的2D角色控制器,附源码_哔哩哔哩_bilibili来自Youtuber Tarodev中文字幕请开启CC字幕视频内源码: https://github.com/Matthew-J-Spencer/Ultimate-2D-Controller额外付费部分: https://www.patreon.com/tarodev了解如何制作一个优秀的玩家控制器。这个Unity角色控制器是使用自定义的物理组件制作的,并包含一些隐藏的平台游戏技巧,让玩家体验到优https://www.bilibili.com/video/BV14S4y1o79L?spm_id_from=333.851.header_right.history_list.click

源码:GitHub - Matthew-J-Spencer/Ultimate-2D-Controller: A great starting point for your 2D controller. Making use of all the hidden tricks like coyote, buffered actions, speedy apex, anti grav apex, etcA great starting point for your 2D controller. Making use of all the hidden tricks like coyote, buffered actions, speedy apex, anti grav apex, etc - GitHub - Matthew-J-Spencer/Ultimate-2D-Controller: A great starting point for your 2D controller. Making use of all the hidden tricks like coyote, buffered actions, speedy apex, anti grav apex, etchttps://github.com/Matthew-J-Spencer/Ultimate-2D-ControllerTarodev is creating Game dev and programming tutorials | PatreonBecome a patron of Tarodev today: Get access to exclusive content and experiences on the world’s largest membership platform for artists and creators.https://www.patreon.com/tarodev

学习内容:

学习好一个2D控制器源码是至关重要的,本素材中作者直接无需添加任何rigibody2D和Collider2D的组件,而是直接用代码来实现玩家的碰撞检测。

创建好一个Ground(用Tile)然后再将它的Layer设置为Ground

创建一个空对象名字叫Player再创建一个空对象叫Viusal给它Audio Source以及新组件Trail Renderer,当你在移动角色的时候该组件会产生一个细的运动轨迹,再创建一个Sprite并给它Sprite Renderer以及Animator

最后给它一个Particals作为总的管理Partical System的再创建移动跳跃落地所需要的Partical System(具体参数源码有)

搞完这些后即可进入编写代码部分:

首先我们要编写的是一个接口负责监控玩家的键盘输入命令,另外一个结构体FrameInput是负责玩家键盘的xy轴的输入,以及射线检测的结构体RayRange.

可以看到我们并没有继承MonoBehaviour,该脚本不需要作为组件挂载,而是给其它类调用

  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. namespace TarController
  5. {
  6. public struct FrameInput
  7. {
  8. public float X;
  9. public bool JumpDown;
  10. public bool JumpUp;
  11. }
  12. public interface IPlayerInterface
  13. {
  14. public FrameInput frameInput { get; }
  15. public Vector3 Velocity { get; }
  16. public bool FrameJumped { get; }
  17. public bool FrameLanded { get; }
  18. public bool Grounded { get; }
  19. public Vector3 RawMovement { get; }
  20. }
  21. public struct RayRange
  22. {
  23. public RayRange(float x1,float y1,float x2,float y2,Vector2 dir)
  24. {
  25. Start = new Vector2(x1, y1);
  26. End = new Vector2(x2, y2);
  27. Dir = dir;
  28. }
  29. public readonly Vector2 Start, End, Dir;
  30. }
  31. }

其次编写的是我们上面提到的能够不使用其它多余组件实现多种移动的CharacterController.cs

完整版如下:

  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using System.Linq;
  5. namespace TarController
  6. {
  7. public class CharacterController : MonoBehaviour, IPlayerInterface
  8. {
  9. //实现IPlayerInterface的接口
  10. public FrameInput frameInput { get; private set; }
  11. public Vector3 Velocity { get; private set; }
  12. public bool FrameJumped { get; private set; }
  13. public bool FrameLanded { get; private set; }
  14. public bool Grounded => collDown;
  15. public Vector3 RawMovement { get; private set; }
  16. private Vector3 lastPosition;
  17. private float currentHorizontalSpeed, currentVerticalSpeed;
  18. //为了防止游戏开始时碰撞体还没生成需要等0.5s ,nameof函数的string类型
  19. bool _actived;
  20. private void Awake()=>Invoke(nameof(Activated),0.5f );
  21. void Activated() => _actived = true;
  22. void Update()
  23. {
  24. if (!_actived)
  25. return;
  26. //计算速度
  27. Velocity = (transform.position - lastPosition) / Time.deltaTime;
  28. lastPosition = transform.position;
  29. CatchInput();
  30. RunCollisionCheck();
  31. CalculateWalk();
  32. CalculateJumpApex();
  33. CalculateGravity();
  34. CalculateJump();
  35. MoveCharacter();
  36. }
  37. #region Input System
  38. private void CatchInput()
  39. {
  40. frameInput = new FrameInput
  41. {
  42. X = Input.GetAxisRaw("Horizontal"),
  43. JumpDown = Input.GetButtonDown("Jump"),//按下跳跃
  44. JumpUp = Input.GetButtonUp("Jump") //按起跳跃
  45. };
  46. if (frameInput.JumpDown)
  47. {
  48. lastJumpPressed = Time.time;
  49. }
  50. }
  51. #endregion
  52. #region Collison
  53. [Header("Collision")]
  54. [SerializeField] private Bounds characterBounds; //边界长方体
  55. [SerializeField] private LayerMask groundLayer;
  56. [SerializeField] private int detectorCount = 3;
  57. [SerializeField] private float detectorLength = 0.1f;
  58. [SerializeField, Range(0.1f, 0.3f)] private float rayBuffer = 0.1f;
  59. private RayRange raysUp, raysDown, raysLeft, raysRight;
  60. bool collUp, collDown, collLeft, collRight;
  61. private float timeLeftGrounded;
  62. private void RunCollisionCheck()
  63. {
  64. //生成射线
  65. CaculateRayRanged();
  66. //这个状态是在地面上
  67. FrameLanded = false;
  68. var groundedCheck = RunDetection(raysDown);
  69. if(collDown&& !groundedCheck)
  70. {
  71. timeLeftGrounded = Time.time;
  72. }
  73. //目的是让玩家离开地面一小段距离时还能进行跳跃
  74. else if(!collDown && groundedCheck)
  75. {
  76. coyoteUsable = true;
  77. FrameLanded = true;
  78. }
  79. collDown = groundedCheck;
  80. collUp = RunDetection(raysUp);
  81. collLeft = RunDetection(raysLeft);
  82. collRight = RunDetection(raysRight);
  83. bool RunDetection(RayRange range)
  84. {
  85. return EvaluateRayPositions(range).Any(point => Physics2D.Raycast(point, range.Dir, detectorLength, groundLayer));
  86. }
  87. }
  88. //用射线来判断是否在地面上
  89. private void CaculateRayRanged()
  90. {
  91. var b = new Bounds(transform.position, characterBounds.size);
  92. raysDown = new RayRange (b.min.x + rayBuffer, b.min.y, b.max.x-rayBuffer, b.min.y,Vector2.down);
  93. raysUp = new RayRange (b.min.x + rayBuffer, b.max.y, b.max.x-rayBuffer, b.max.y, Vector2.up);
  94. raysLeft = new RayRange (b.min.x, b.min.y + rayBuffer, b.min.x, b.max.y - rayBuffer, Vector2.left);
  95. raysRight = new RayRange(b.max.x, b.min.y + rayBuffer, b.max.x, b.max.y - rayBuffer, Vector2.right);
  96. }
  97. //这里不知道什么意思
  98. private IEnumerable<Vector2> EvaluateRayPositions(RayRange range)
  99. {
  100. for (int i = 0; i < detectorCount; i++)
  101. {
  102. var t = (float)i / (detectorCount - 1);
  103. yield return Vector2.Lerp(range.Start, range.End, t);
  104. }
  105. }
  106. private void OnDrawGizmos()
  107. {
  108. //Bounds
  109. Gizmos.color = Color.yellow;
  110. Gizmos.DrawWireCube(transform.position + characterBounds.center, characterBounds.size);
  111. //画射线
  112. if (!Application.isPlaying)
  113. {
  114. CaculateRayRanged();
  115. Gizmos.color = Color.blue;
  116. foreach (var range in new List<RayRange> { raysUp,raysRight,raysDown,raysLeft})
  117. {
  118. foreach (var point in EvaluateRayPositions(range))
  119. {
  120. Gizmos.DrawRay(point, range.Dir * detectorLength);
  121. }
  122. }
  123. }
  124. if (!Application.isPlaying)
  125. return;
  126. //未来的位置
  127. Gizmos.color = Color.red;
  128. var move = new Vector3(currentHorizontalSpeed, currentVerticalSpeed) * Time.deltaTime;
  129. Gizmos.DrawWireCube(transform.position + move, characterBounds.size);
  130. }
  131. #endregion
  132. #region Walk
  133. /*
  134. 要说明一定,当到最高点apex的时候,允许有一定的调整速度,即apexBonus
  135. */
  136. [Header("Walking")]
  137. [SerializeField] float moveClamp = 13f; //最大速度
  138. [SerializeField] float accleration = 90f; //加速度
  139. [SerializeField] float deAccleration = 60f; //减速度
  140. [SerializeField] float apexBonus = 2f;
  141. private void CalculateWalk()
  142. {
  143. if(frameInput.X != 0)
  144. {
  145. currentHorizontalSpeed +=frameInput.X * accleration * Time.deltaTime;
  146. currentHorizontalSpeed = Mathf.Clamp(currentHorizontalSpeed, -moveClamp, moveClamp);
  147. //奖励速度,当跳跃到最高点时
  148. //Mathf.Sign() 如果是0或正数就返回1,负数则返回-1 //最高点apex
  149. var _apexBouns = Mathf.Sign(frameInput.X) * apexBonus * apexPoints;
  150. currentHorizontalSpeed += _apexBouns * Time.deltaTime;
  151. }
  152. //当你键盘没有输入X的速度就减速
  153. else
  154. {
  155. currentHorizontalSpeed = Mathf.MoveTowards(currentHorizontalSpeed, 0, deAccleration * Time.deltaTime);
  156. }
  157. //当碰到墙上时
  158. if(currentHorizontalSpeed >0 && collRight || currentHorizontalSpeed <0 && collLeft)
  159. {
  160. currentHorizontalSpeed = 0;
  161. }
  162. }
  163. #endregion
  164. #region Jump
  165. /*
  166. 跳跃分为小跳和大跳
  167. 当按下跳跃的时候y轴的速度等于跳跃高度,同时开始计时离开地面的时间,关闭coyote,正在跳跃为true,早点结束跳跃为false
  168. 当按起跳跃键的时候,判断脚没碰到地面,有y轴方向的速度,早点结束跳跃为true
  169. 当头顶碰到物体的时候直接将y轴速度设置为0
  170. 同时还有一个判断在跳跃最高点,用插值函数作为fallspeed
  171. */
  172. [Header("Jumping")]
  173. [SerializeField] float jumpHeight = 30f;
  174. [SerializeField] float jumpEarlyGravityModifier = 3;
  175. [SerializeField] float jumpApexThreshold = 10f; //当跳跃到最高点时有一段反重力和小助推效果
  176. [SerializeField] float coyoteTImeThreshold = 0.1f;
  177. [SerializeField] float jumpBuffered = 0.1f;
  178. private float apexPoints; //当跳到最高点时值为1
  179. private float lastJumpPressed; //记录按下跳跃的时间
  180. private bool coyoteUsable;
  181. private bool endedjumpEarly = true;
  182. private bool CanUseCoyote => coyoteUsable && !collDown && coyoteTImeThreshold + timeLeftGrounded > Time.time; //允许玩家在离开平台的几毫秒时间内仍然能跳跃
  183. private bool HasBufferJump => collDown && jumpBuffered + lastJumpPressed > Time.time; //跳跃缓冲
  184. private void CalculateJumpApex()
  185. {
  186. if (!collDown)
  187. {
  188. apexPoints = Mathf.InverseLerp(jumpApexThreshold, 0,Mathf.Abs( Velocity.y));
  189. fallSpeed = Mathf.Lerp(minFallSpeed, maxFallSpeed, apexPoints);
  190. }
  191. else
  192. {
  193. apexPoints = 0;
  194. }
  195. }
  196. private void CalculateJump()
  197. {
  198. //大跳
  199. if (frameInput.JumpDown && CanUseCoyote || HasBufferJump)
  200. {
  201. currentVerticalSpeed = jumpHeight;
  202. endedjumpEarly = false;
  203. coyoteUsable = false;
  204. timeLeftGrounded = float.MinValue;
  205. FrameJumped = true;
  206. }
  207. else
  208. {
  209. FrameJumped = false;
  210. }
  211. //小跳(在跳跃的时候很快就松开跳跃键)
  212. if (frameInput.JumpUp && !collDown && !endedjumpEarly && Velocity.y >0)
  213. {
  214. endedjumpEarly = true;
  215. }
  216. //如果头顶撞到了
  217. if (collUp)
  218. {
  219. if(currentVerticalSpeed > 0)
  220. {
  221. currentVerticalSpeed = 0;
  222. }
  223. }
  224. }
  225. #endregion
  226. #region Gravity
  227. [Header("Gravity")]
  228. [SerializeField] float fallClamp = -40f;
  229. [SerializeField] float minFallSpeed = 80f;
  230. [SerializeField] float maxFallSpeed = 120f;
  231. private float fallSpeed;
  232. /*
  233. 先判断是否在地面上,如果在地面上y轴的速度为0,如果在下降过程中,则再判断是否是小跳,小跳则加快降落速度,否则是正常减速度
  234. 最后再限制一下最大下落速度
  235. */
  236. private void CalculateGravity()
  237. {
  238. if (collDown)
  239. {
  240. if (currentVerticalSpeed < 0)
  241. currentVerticalSpeed = 0;
  242. }
  243. else
  244. {
  245. //判断是否大小跳然后再根据选择下降速度
  246. var fallingSpeed = endedjumpEarly && currentVerticalSpeed > 0 ? fallSpeed * jumpEarlyGravityModifier : fallSpeed;
  247. currentVerticalSpeed -= fallingSpeed * Time.deltaTime;
  248. if (currentVerticalSpeed < fallClamp) currentVerticalSpeed = fallClamp;
  249. }
  250. }
  251. #endregion
  252. #region Move
  253. [Header("Move")]
  254. [SerializeField, Tooltip("Raising this value increases collision accuracy at the cost of performance.")]
  255. private int freeColliderIterations = 10;
  256. //我们投射我们的边界来避免被接下来的碰撞体
  257. private void MoveCharacter()
  258. {
  259. var pos = transform.position;
  260. RawMovement = new Vector3(currentHorizontalSpeed, currentVerticalSpeed);
  261. var move = RawMovement * Time.deltaTime;
  262. var furtherPos = move + pos;
  263. //检测下一个位置的碰撞,如果没有发生碰撞就停止检测
  264. var hit = Physics2D.OverlapBox(furtherPos, characterBounds.size, 0, groundLayer);
  265. if(!hit)
  266. {
  267. transform.position += move;
  268. return;
  269. }
  270. //否则找个可以移动的点
  271. var positionToMoveTo = transform.position;
  272. for (int i = 1; i < freeColliderIterations; i++)
  273. {
  274. var t = (float)i / freeColliderIterations;
  275. var posToTry = Vector2.Lerp(pos, furtherPos, t);
  276. if (Physics2D.OverlapBox(posToTry, characterBounds.size, 0, groundLayer))
  277. {
  278. transform.position = positionToMoveTo;
  279. if(i == 1)
  280. {
  281. if (currentVerticalSpeed < 0)
  282. currentVerticalSpeed = 0;
  283. var dir = transform.position - hit.transform.position;
  284. transform.position += dir.normalized * move.magnitude;
  285. }
  286. return;
  287. }
  288. positionToMoveTo = posToTry;
  289. }
  290. }
  291. #endregion
  292. }
  293. }

解析版如下:

首先我们要实现前面提到的接口里面的所有成员(这里是属性)

  1. //实现IPlayerInterface的接口
  2. public FrameInput frameInput { get; private set; }
  3. public Vector3 Velocity { get; private set; }
  4. public bool FrameJumped { get; private set; }
  5. public bool FrameLanded { get; private set; }
  6. public bool Grounded => collDown;
  7. public Vector3 RawMovement { get; private set; }

然后我们currentHorizontalSpeed, currentVerticalSpeed记录我们的xy轴方向上的速度。

这段是作者说明为了防止游戏运行时碰撞体还没有完成生成而延迟0.5s使用Awake()函数

  1. //为了防止游戏开始时碰撞体还没生成需要等0.5s ,nameof函数的string类型
  2. bool _actived;
  3. private void Awake()=>Invoke(nameof(Activated),0.5f );
  4. void Activated() => _actived = true;
  1. if (!_actived)
  2. return;
  3. //计算速度
  4. Velocity = (transform.position - lastPosition) / Time.deltaTime;
  5. lastPosition = transform.position;

然后我们分模块解析各个函数的意义,每个模块都用#region 和 #endregion来分块管理

首先是Input System

用Unity中Input类自带的来键盘输入,赋值给我们前面创建的结构体FrameInput,frameInput.JumpDown记录我们最后按下跳跃的时间

  1. #region Input System
  2. private void CatchInput()
  3. {
  4. frameInput = new FrameInput
  5. {
  6. X = Input.GetAxisRaw("Horizontal"),
  7. JumpDown = Input.GetButtonDown("Jump"),//按下跳跃
  8. JumpUp = Input.GetButtonUp("Jump") //按起跳跃
  9. };
  10. if (frameInput.JumpDown)
  11. {
  12. lastJumpPressed = Time.time;
  13. }
  14. }
  15. #endregion

然后是Walk模块

用+=来加速,用Mathf.Clamp(限制它的最大速度),而apexBouns则是玩家跳跃到最高点的时候能进行小范围的移动来控制下落点;当你没有输入X方向的输入的时候,Mathf.MoveTowards()来减速,最后当你撞墙的时候你的currentHorizontalSpeed = 0;

  1. #region Walk
  2. /*
  3. 要说明一定,当到最高点apex的时候,允许有一定的调整速度,即apexBonus
  4. */
  5. [Header("Walking")]
  6. [SerializeField] float moveClamp = 13f; //最大速度
  7. [SerializeField] float accleration = 90f; //加速度
  8. [SerializeField] float deAccleration = 60f; //减速度
  9. [SerializeField] float apexBonus = 2f;
  10. private void CalculateWalk()
  11. {
  12. if(frameInput.X != 0)
  13. {
  14. currentHorizontalSpeed +=frameInput.X * accleration * Time.deltaTime;
  15. currentHorizontalSpeed = Mathf.Clamp(currentHorizontalSpeed, -moveClamp, moveClamp);
  16. //奖励速度,当跳跃到最高点时
  17. //Mathf.Sign() 如果是0或正数就返回1,负数则返回-1 //最高点apex
  18. var _apexBouns = Mathf.Sign(frameInput.X) * apexBonus * apexPoints;
  19. currentHorizontalSpeed += _apexBouns * Time.deltaTime;
  20. }
  21. //当你键盘没有输入X的速度就减速
  22. else
  23. {
  24. currentHorizontalSpeed = Mathf.MoveTowards(currentHorizontalSpeed, 0, deAccleration * Time.deltaTime);
  25. }
  26. //当碰到墙上时
  27. if(currentHorizontalSpeed >0 && collRight || currentHorizontalSpeed <0 && collLeft)
  28. {
  29. currentHorizontalSpeed = 0;
  30. }
  31. }
  32. #endregion

跳跃部分分为大跳和小跳,根据你是否过早松开跳跃键来判断。需要注意的是coyote部分的代码使用于当你在台阶上离开地面的几毫秒时间你仍然能进行跳跃

  1. #region Jump
  2. /*
  3. 跳跃分为小跳和大跳
  4. 当按下跳跃的时候y轴的速度等于跳跃高度,同时开始计时离开地面的时间,关闭coyote,正在跳跃为true,早点结束跳跃为false
  5. 当按起跳跃键的时候,判断脚没碰到地面,有y轴方向的速度,早点结束跳跃为true
  6. 当头顶碰到物体的时候直接将y轴速度设置为0
  7. 同时还有一个判断在跳跃最高点,用插值函数作为fallspeed
  8. */
  9. [Header("Jumping")]
  10. [SerializeField] float jumpHeight = 30f;
  11. [SerializeField] float jumpEarlyGravityModifier = 3;
  12. [SerializeField] float jumpApexThreshold = 10f; //当跳跃到最高点时有一段反重力和小助推效果
  13. [SerializeField] float coyoteTImeThreshold = 0.1f;
  14. [SerializeField] float jumpBuffered = 0.1f;
  15. private float apexPoints; //当跳到最高点时值为1
  16. private float lastJumpPressed; //记录按下跳跃的时间
  17. private bool coyoteUsable;
  18. private bool endedjumpEarly = true;
  19. private bool CanUseCoyote => coyoteUsable && !collDown && coyoteTImeThreshold + timeLeftGrounded > Time.time; //允许玩家在离开平台的几毫秒时间内仍然能跳跃
  20. private bool HasBufferJump => collDown && jumpBuffered + lastJumpPressed > Time.time; //跳跃缓冲
  21. private void CalculateJumpApex()
  22. {
  23. if (!collDown)
  24. {
  25. apexPoints = Mathf.InverseLerp(jumpApexThreshold, 0,Mathf.Abs( Velocity.y));
  26. fallSpeed = Mathf.Lerp(minFallSpeed, maxFallSpeed, apexPoints);
  27. }
  28. else
  29. {
  30. apexPoints = 0;
  31. }
  32. }
  33. private void CalculateJump()
  34. {
  35. //大跳
  36. if (frameInput.JumpDown && CanUseCoyote || HasBufferJump)
  37. {
  38. currentVerticalSpeed = jumpHeight;
  39. endedjumpEarly = false;
  40. coyoteUsable = false;
  41. timeLeftGrounded = float.MinValue;
  42. FrameJumped = true;
  43. }
  44. else
  45. {
  46. FrameJumped = false;
  47. }
  48. //小跳(在跳跃的时候很快就松开跳跃键)
  49. if (frameInput.JumpUp && !collDown && !endedjumpEarly && Velocity.y >0)
  50. {
  51. endedjumpEarly = true;
  52. }
  53. //如果头顶撞到了
  54. if (collUp)
  55. {
  56. if(currentVerticalSpeed > 0)
  57. {
  58. currentVerticalSpeed = 0;
  59. }
  60. }
  61. }
  62. #endregion

然后到了下落部分,同样根据你是大跳还是小跳决定你的下落速度

  1. #region Gravity
  2. [Header("Gravity")]
  3. [SerializeField] float fallClamp = -40f;
  4. [SerializeField] float minFallSpeed = 80f;
  5. [SerializeField] float maxFallSpeed = 120f;
  6. private float fallSpeed;
  7. /*
  8. 先判断是否在地面上,如果在地面上y轴的速度为0,如果在下降过程中,则再判断是否是小跳,小跳则加快降落速度,否则是正常减速度
  9. 最后再限制一下最大下落速度
  10. */
  11. private void CalculateGravity()
  12. {
  13. if (collDown)
  14. {
  15. if (currentVerticalSpeed < 0)
  16. currentVerticalSpeed = 0;
  17. }
  18. else
  19. {
  20. //判断是否大小跳然后再根据选择下降速度
  21. var fallingSpeed = endedjumpEarly && currentVerticalSpeed > 0 ? fallSpeed * jumpEarlyGravityModifier : fallSpeed;
  22. currentVerticalSpeed -= fallingSpeed * Time.deltaTime;
  23. if (currentVerticalSpeed < fallClamp) currentVerticalSpeed = fallClamp;
  24. }
  25. }
  26. #endregion

然后是Collision部分的检测

  1. region Collison
  2. [Header("Collision")]
  3. [SerializeField] private Bounds characterBounds; //边界长方体
  4. [SerializeField] private LayerMask groundLayer;
  5. [SerializeField] private int detectorCount = 3;
  6. [SerializeField] private float detectorLength = 0.1f;
  7. [SerializeField, Range(0.1f, 0.3f)] private float rayBuffer = 0.1f;
  8. private RayRange raysUp, raysDown, raysLeft, raysRight;
  9. bool collUp, collDown, collLeft, collRight;
  10. private float timeLeftGrounded;
  11. private void RunCollisionCheck()
  12. {
  13. //生成射线
  14. CaculateRayRanged();
  15. //这个状态是在地面上
  16. FrameLanded = false;
  17. var groundedCheck = RunDetection(raysDown);
  18. if(collDown&& !groundedCheck)
  19. {
  20. timeLeftGrounded = Time.time;
  21. }
  22. //目的是让玩家离开地面一小段距离时还能进行跳跃
  23. else if(!collDown && groundedCheck)
  24. {
  25. coyoteUsable = true;
  26. FrameLanded = true;
  27. }
  28. collDown = groundedCheck;
  29. collUp = RunDetection(raysUp);
  30. collLeft = RunDetection(raysLeft);
  31. collRight = RunDetection(raysRight);
  32. bool RunDetection(RayRange range)
  33. {
  34. return EvaluateRayPositions(range).Any(point => Physics2D.Raycast(point, range.Dir, detectorLength, groundLayer));
  35. }
  36. }
  37. //用射线来判断是否在地面上
  38. private void CaculateRayRanged()
  39. {
  40. var b = new Bounds(transform.position, characterBounds.size);
  41. raysDown = new RayRange (b.min.x + rayBuffer, b.min.y, b.max.x-rayBuffer, b.min.y,Vector2.down);
  42. raysUp = new RayRange (b.min.x + rayBuffer, b.max.y, b.max.x-rayBuffer, b.max.y, Vector2.up);
  43. raysLeft = new RayRange (b.min.x, b.min.y + rayBuffer, b.min.x, b.max.y - rayBuffer, Vector2.left);
  44. raysRight = new RayRange(b.max.x, b.min.y + rayBuffer, b.max.x, b.max.y - rayBuffer, Vector2.right);
  45. }
  46. //这里不知道什么意思
  47. private IEnumerable<Vector2> EvaluateRayPositions(RayRange range)
  48. {
  49. for (int i = 0; i < detectorCount; i++)
  50. {
  51. var t = (float)i / (detectorCount - 1);
  52. yield return Vector2.Lerp(range.Start, range.End, t);
  53. }
  54. }
  55. private void OnDrawGizmos()
  56. {
  57. //Bounds
  58. Gizmos.color = Color.yellow;
  59. Gizmos.DrawWireCube(transform.position + characterBounds.center, characterBounds.size);
  60. //画射线
  61. if (!Application.isPlaying)
  62. {
  63. CaculateRayRanged();
  64. Gizmos.color = Color.blue;
  65. foreach (var range in new List<RayRange> { raysUp,raysRight,raysDown,raysLeft})
  66. {
  67. foreach (var point in EvaluateRayPositions(range))
  68. {
  69. Gizmos.DrawRay(point, range.Dir * detectorLength);
  70. }
  71. }
  72. }
  73. if (!Application.isPlaying)
  74. return;
  75. //未来的位置
  76. Gizmos.color = Color.red;
  77. var move = new Vector3(currentHorizontalSpeed, currentVerticalSpeed) * Time.deltaTime;
  78. Gizmos.DrawWireCube(transform.position + move, characterBounds.size);
  79. }
  80. #endregion

最后是真正用于移动的Move()

  1. #region Move
  2. [Header("Move")]
  3. [SerializeField, Tooltip("Raising this value increases collision accuracy at the cost of performance.")]
  4. private int freeColliderIterations = 10;
  5. //我们投射我们的边界来避免被接下来的碰撞体
  6. private void MoveCharacter()
  7. {
  8. var pos = transform.position;
  9. RawMovement = new Vector3(currentHorizontalSpeed, currentVerticalSpeed);
  10. var move = RawMovement * Time.deltaTime;
  11. var furtherPos = move + pos;
  12. //检测下一个位置的碰撞,如果没有发生碰撞就停止检测
  13. var hit = Physics2D.OverlapBox(furtherPos, characterBounds.size, 0, groundLayer);
  14. if(!hit)
  15. {
  16. transform.position += move;
  17. return;
  18. }
  19. //否则找个可以移动的点
  20. var positionToMoveTo = transform.position;
  21. for (int i = 1; i < freeColliderIterations; i++)
  22. {
  23. var t = (float)i / freeColliderIterations;
  24. var posToTry = Vector2.Lerp(pos, furtherPos, t);
  25. if (Physics2D.OverlapBox(posToTry, characterBounds.size, 0, groundLayer))
  26. {
  27. transform.position = positionToMoveTo;
  28. if(i == 1)
  29. {
  30. if (currentVerticalSpeed < 0)
  31. currentVerticalSpeed = 0;
  32. var dir = transform.position - hit.transform.position;
  33. transform.position += dir.normalized * move.magnitude;
  34. }
  35. return;
  36. }
  37. positionToMoveTo = posToTry;
  38. }
  39. }
  40. #endregion
  41. }

最后我们再添加一个CharacterAnimator.cs用于做动画,控制身体转向,播放声音,播放粒子特效

  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using Random = UnityEngine.Random;
  5. namespace TarController
  6. {
  7. public class CharacterAnimator : MonoBehaviour
  8. {
  9. [SerializeField] private Animator anim;
  10. [SerializeField] private AudioSource source;
  11. [SerializeField] private AudioClip[] clips;
  12. [SerializeField] private LayerMask groundMasks;
  13. [SerializeField] private ParticleSystem jumpParticle, lanuchParticle;
  14. [SerializeField] private ParticleSystem moveParticle, landParticle;
  15. [SerializeField] private float maxTilt = 0.1f;
  16. [SerializeField] private float tileSpeed = 1f;
  17. [SerializeField, Range(1f, 3f)] private float maxIdleSpeed = 2f;
  18. [SerializeField] private float maxParticalFallSpeed = -40f;
  19. private ParticleSystem.MinMaxGradient currentGradient;
  20. private IPlayerInterface player;
  21. private bool playerOnGround;
  22. private Vector2 movement;
  23. void Awake() => player = GetComponentInParent<IPlayerInterface>();
  24. void Update()
  25. {
  26. if (player != null)
  27. return;
  28. //Flip
  29. if (player.frameInput.X != 0)
  30. {
  31. transform.localScale = new Vector3(player.frameInput.X >0?1:-1, 1, 1);
  32. }
  33. //跑步的时候播放身体抖动的动画
  34. var targetRotVector = new Vector3(0, 0, Mathf.Lerp(-maxTilt, maxTilt, Mathf.InverseLerp(-1, 1, player.frameInput.X)));
  35. anim.transform.rotation = Quaternion.RotateTowards(anim.transform.rotation,Quaternion.Euler(targetRotVector), tileSpeed * Time.deltaTime);
  36. //跑步的动画
  37. anim.SetFloat(IdleSpeedKey, Mathf.Lerp(1, maxIdleSpeed, Mathf.Abs(player.frameInput.X)));
  38. //降落动画
  39. if (player.FrameLanded)
  40. {
  41. anim.SetTrigger(GroundedKey);
  42. source.PlayOneShot(clips[Random.Range(0, clips.Length)]);
  43. }
  44. //跳跃动画
  45. if (player.FrameJumped)
  46. {
  47. anim.SetTrigger(JumpKey);
  48. anim.ResetTrigger(GroundedKey);
  49. //只有在地面上才会播放粒子(也避免在coyote状态下播放)
  50. if (player.Grounded)
  51. {
  52. SetColor(jumpParticle);
  53. SetColor(lanuchParticle);
  54. jumpParticle.Play();
  55. }
  56. }
  57. //降落的粒子特效
  58. if(!playerOnGround && player.Grounded)
  59. {
  60. playerOnGround = true;
  61. moveParticle.Play();
  62. landParticle.transform.localScale = Vector3.one * Mathf.InverseLerp(0, maxParticalFallSpeed, movement.y);
  63. SetColor(landParticle);
  64. landParticle.Play();
  65. }
  66. else if(playerOnGround && !player.Grounded)
  67. {
  68. playerOnGround = false;
  69. moveParticle.Stop();
  70. }
  71. //检测是否碰到地面
  72. var groundHit = Physics2D.Raycast(transform.position, Vector3.down, 2, groundMasks);
  73. if(groundHit&& groundHit.transform.TryGetComponent(out SpriteRenderer sr))
  74. {
  75. currentGradient = new ParticleSystem.MinMaxGradient(sr.color * 0.9f, sr.color * 1.2f);
  76. SetColor(moveParticle);
  77. }
  78. movement = player.RawMovement;
  79. }
  80. private void OnDisable()
  81. {
  82. moveParticle.Stop();
  83. }
  84. private void OnEnable()
  85. {
  86. moveParticle.Play();
  87. }
  88. private void SetColor(ParticleSystem ps)
  89. {
  90. var main = ps.main;
  91. main.startColor = currentGradient;
  92. }
  93. #region Animation Keys
  94. private static readonly int GroundedKey = Animator.StringToHash("Grounded");
  95. private static readonly int IdleSpeedKey = Animator.StringToHash("IdleSpeed");
  96. private static readonly int JumpKey = Animator.StringToHash("Jump");
  97. #endregion
  98. }
  99. }

在Visual游戏对象的Aniamtor中添加条件 

别忘了修改参数


学习产出:

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/2023面试高手/article/detail/118765
推荐阅读
相关标签
  

闽ICP备14008679号