双击打开SampleScene
创建一个Sprite——Square,命名为Ground,挂载Box Collider 2D,放在场景的下面,缩放至适合宽度
再创建一个Sprite,命名为Player,挂载Box Collider 2D和Rigidbody 2D,并且锁定Z旋转。

角色移动
新建Scripts文件夹,从中新建一个脚本,命名为Player
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| using UnityEngine;
namespace ShootingEditor2D { public class Player : MonoBehaviour { Rigidbody2D m_rigidbody; private void Awake() { m_rigidbody = GetComponent<Rigidbody2D>(); } private void FixedUpdate() { var horizontalAxis = Input.GetAxis("Horizontal");
m_rigidbody.velocity = new Vector2(horizontalAxis * 5, m_rigidbody.velocity.y); } } }
|
挂载在Player上面
角色跳跃
首先我们在角色上创建空子对象,命名为“GroundCheck”;在上面挂载Circle Collider 2D组件,打开“is Trigger”并且把Radius设为0.1,将GroundCheck位置往下移到合适的位置

教程中将Radius设为了0.01,这里为了截图方便暂用0.1半径,上图的is Trigger没有打开,别忘了打开
在Scripts文件夹中新建脚本,命名为Trigger2DCheck
,挂载在GroundCheck上,并将TargetLayer设为“Default”
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
| using UnityEngine;
namespace ShootingEditor2D { public class Trigger2DCheck : MonoBehaviour { public LayerMask TargetLayer;
public int EnterCount;
public bool Triggered { get { return EnterCount > 0; } }
private void OnTriggerEnter2D(Collider2D collision) { if (IsInLayerMask(collision.gameObject, TargetLayer)) { EnterCount++; } }
private void OnTriggerExit2D(Collider2D collision) { if (IsInLayerMask(collision.gameObject, TargetLayer)) { EnterCount--; } }
bool IsInLayerMask(GameObject obj, LayerMask mask) { var layerMaskofObj = 1 << obj.layer; return (layerMaskofObj & mask) > 0; } } }
|
这是一个比较通用的Tirgger脚本,并且包含了一些计数器的思路。
修改Palyer
脚本
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
| using UnityEngine;
namespace ShootingEditor2D { public class Player : MonoBehaviour { private bool m_JumpPressed;
private Trigger2DCheck m_GroundCheck;
Rigidbody2D m_Rigidbody2D; private void Awake() { m_Rigidbody2D = GetComponent<Rigidbody2D>(); m_GroundCheck = transform.Find("GroundCheck").GetComponent<Trigger2DCheck>(); }
private void Update() { if(Input.GetButtonDown("Jump")) m_JumpPressed = true; }
private void FixedUpdate() { var horizontalAxis = Input.GetAxis("Horizontal");
m_Rigidbody2D.velocity = new Vector2(horizontalAxis * 5, m_Rigidbody2D.velocity.y);
var isOnGround = m_GroundCheck.Triggered;
if (m_JumpPressed && isOnGround) { m_Rigidbody2D.velocity = new Vector2(m_Rigidbody2D.velocity.x, 5); }
m_JumpPressed = false;
} } }
|
这样就可以正常跳跃了