Unity创建移动平台并使Player随其移动

 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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class MovingPlatform : MonoBehaviour
{
    // Start is called before the first frame update

    public float speed;
    public float waitTime;
    public Transform[] movePos;

    private int i;
    private float waittime;
    private Transform playerDefTransform;

    void Start()
    {
        i = 1;

        playerDefTransform = GameObject.FindGameObjectWithTag("Player").transform.parent;

    }

    // Update is called once per frame
    void Update()
    {
        // 悬浮地面向坐标i移动,若当前的坐标已到达i坐标且等待时间为0(不为0则减到0为止),则改变i的值,使其移动到下一个坐标,并且将等待时间重新赋值。
        // 所移动的坐标列表只能为两个值
        transform.position = Vector2.MoveTowards(transform.position, movePos[i].position, speed * Time.deltaTime);
        // Vector2.Distance(a,b); = a与b之间的距离

        if (Vector2.Distance(transform.position,movePos[i].position)<0.1f)
        {
            if ( waittime < 0.0f)
            {
                if (i==0)
                {
                    i = 1;
                }
                else
                {
                    i = 0;
                }
                waittime = waitTime;
            }
        }
        else
        {
            waittime -= Time.deltaTime;
        }

    }

    

        // 当移动平台与标签为“Player”的Game-object的“Boxcollider2D”发生碰撞时,将Game-object的坐标设置为移动平台的子对象,使其一同移动

        void OnTriggerEnter2D(Collider2D other)
        {
            
            if (other.CompareTag("Player")&&other.GetType().ToString() == "UnityEngine.BoxCollider2D")
            {
                other.gameObject.transform.parent = gameObject.transform;
            }
        }

        // 停止触发器

        void OnTriggerExit2D(Collider2D other)
        {
            if (other.CompareTag("Player") && other.GetType().ToString() == "UnityEngine.BoxCollider2D")
            {
                other.gameObject.transform.parent = playerDefTransform;
            }
        }
}

回到unity编辑器页面将改脚本文件挂载到对应的Game-object上,给予脚本必须的值即可。