单向平台
从底部可以穿过平台跳到平台上面
1.添加平台
添加平台图片到场景中,命名为OneWayPlatform
添加Edge Collider 2D,设置Offset中Y为0.5
因角色在平台上不是地面,显示状态为Jump,需设置平台上落地
添加Layer:Platform
添加Tag:Platform
设置OneWatPlatform的Tag和Layer为Platform
进入Player预制体中,设置WhatIsGround添加Platform
2.添加平台效果
添加Platform Effector 2D,设置Surface Arc角度为110,并设置Edge Collider 2D中Use By Effector为tru,
3.制作预制体
在Prefabs文件夹下,新建文件夹LevelMechanics,将OneWayPlatform拖入到文件夹下制成预制体
4.移动平台
新建空节点MovingPlatform,添加平台预制体到节点上
再新建3个空节点,分别命名为Point_1,Point_2,Point_3,表示平台的移动点
设置移动点位置分别是偏左、偏右、偏右上,使平台在3点移动
新建脚本MovingPlatform.cs,添加组件到MovingPlatform节点上绑定
添加参数
public Transform[] points; //移动点
public float moveSpeed; //移动速度
public int currentPoint; //当前点
public Transform platForm; //平台
在Unity中,对应绑定参数
Update()中,实现移动
void Update()
{
//platForm位置
platForm.position = Vector3.MoveTowards(platForm.position, points[currentPoint].position, moveSpeed * Time.deltaTime);
if(Vector3.Distance(platForm.position, points[currentPoint].position) < 0.05f)
{
currentPoint++;
if(currentPoint >= points.Length)
{
currentPoint = 0;
}
}
}
移动到3点时,有点诡异,可将2点设置到数组后,使移动为1-2-3-2-1…
5.带动角色一起移动
前面几步设置后,当角色跳到平台时,平台自行移动,角色却不跟随
PlayerController.cs中,添加碰撞检测函数
检测碰撞对象是Platform时,在进入碰撞设置Player父节点为Platform,使跟随平台移动
出碰撞时,设置Player父节点为null,即为当前场景,取消跟随平台移动
private void OnCollisionEnter2D(Collision2D other)
{
if (other.transform.CompareTag("Platform"))
{
transform.parent = other.transform;
}
}
private void OnCollisionExit2D(Collision2D other)
{
if (other.transform.CompareTag("Platform"))
{
transform.parent = null;
}
}