类似空洞骑士 马里奥等各种2D游戏,其中都存在单向平台。
单向平台:角色可以从下穿过平台停在平台上,也可以从平台上按下或往下跳穿过平台
这里用Unity实现角色能跳上平台,也能按’下’穿过平台
- 平台需要使用
Rigidbody2D
Collider2D
Platform Effector 2D
组件 Collider2D
中的Used By Effector
属性需要为truePlatform Effector 2D
中的Use One Way
需要为true
脚本编辑:
private PlatformEffector2D platformEffector2D;
//判断平台是否需要翻转
private bool ifRotate;
//平台翻转时长
private float waitTime = 0.5f;
// Start is called before the first frame update
void Start()
{
platformEffector2D = GetComponent<PlatformEffector2D>();
ifRotate = false;
}
// Update is called once per frame
void Update()
{
//检测到 下 按键后,实现翻转
if(Input.GetKeyDown(KeyCode.DownArrow)) {
platformEffector2D.rotationalOffset = 180;
ifRotate = true;
}
if(ifRotate)
{
if(waitTime > 0)
{
waitTime -= Time.deltaTime;
}
else
{
//时间到后平台翻转回
waitTime = 0.5f;
ifRotate = false;
platformEffector2D.rotationalOffset = 0;
}
}
}
单项平台的实现是通过Platform Effector 2D检测碰撞角度实现,初始状态下
rotationalOffset
为0,则只检测平台上方的碰撞,因此角色能从平台下方穿过停在平台上方。翻转则是检测按键后使rotationalOffset
为180,过一段时间后翻转回