【Unity2D】制作可以左右移动的平台

学习目标:

游戏中经常出现各种可以移动的平台,如空洞骑士和死亡细胞里面的电梯。那我们也可以制作一个可以一直左右移动的平台。

先用SunnyLand的图片来实现一个简单的左右移动的平台

这个是SunnyLand的下载地址


学习内容:

先拖入一张图片两个空对象在图片中,如果我想左右移动的话保持y的坐标一致即可

然后我们创建一个脚本叫MovingPlatform。

内容如下:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class MovingPlatform : MonoBehaviour
{
    public float moveSpeed;
    private float waitTime;
    public float totalTime;

    public Transform[] movePos;
    private Transform playerTransform;
    //i是1则右,是0则变成左
    private int i;

    void Start()
    {
        playerTransform = GameObject.FindGameObjectWithTag("Player").transform.parent;
        i = 1;
        waitTime = totalTime;
    }

    
    void Update()
    {
        transform.position = Vector2.MoveTowards(transform.position, movePos[i].position, moveSpeed * Time.deltaTime);
        //如果两点的距离小于等于0.1
        if (Vector2.Distance(transform.position, movePos[i].position) <= 0.1f)
        {
            //且等待时间小于0
            if (waitTime < 0)
            {
                if (i == 1)
                {
                    i = 0;
                }
                else
                {
                    i = 1;
                }

                waitTime = totalTime;
            }
            else
            {
                waitTime -= Time.deltaTime;
            }
        }
    }
    private void OnTriggerEnter2D(Collider2D other)
    {
        if(other.gameObject.CompareTag("Player") && other.GetType().ToString() == "UnityEngine.CapsuleCollider2D")
        {
            //将movingPlateform作为player的父对象
            other.gameObject.transform.parent = gameObject.transform;
        }
    }
    private void OnTriggerExit2D(Collider2D other)
    {
        if (other.gameObject.CompareTag("Player") && other.GetType().ToString() == "UnityEngine.CapsuleCollider2D")
        {
            //将movingPlateform作为player的父对象
            other.gameObject.transform.parent = playerTransform;
        }
    }
}

补充一点为什么要作为父对象,因为站上去的时候人物需要随着movingplatform进行移动,如果不是父对象的话人物是不能跟着平台移动。
别忘了给movingplatform加上左右坐标的位置

还要添加一个碰撞器,  要和人物产生碰撞

如果想要人物在平台上跳跃。需要在PlayerController的脚本上给个判断

void CheckOnGround()
    {
        isGround = circoll2D.IsTouchingLayers(ground) || circoll2D.IsTouchingLayers(movingPlatform);
    }


学习产出:

能跳跃并且跟着动,可以下我hierarchy面板的父对象关系。

  • 5
    点赞
  • 25
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值