Unity链表的应用之蛇形动画

实现的功能:单击创建出一个Cube,跟随前一个运动,位置是前一个Cube的前一秒的位置,类似贪吃蛇。

在场景中创建两个Cube,给一个添加紫色的材质球,另一个添加绿色的材质球。

给紫色Cube添加一个Cubemove脚本,给绿色Cube添加一个FollowCube脚本。

把绿色的Cube拖成预设体,大小改小一点。



紫色Cube挂载的脚本代码:

using UnityEngine;
using System.Collections;

public class Cubemove : MonoBehaviour
{
    float timer;//游戏运行时间
    float nowTimer;//当前时间
    FollowCube tail;//指向最后生成的
    FollowCube next;//实例化的第二个Cube,
    Vector3 oldPos;//记录Cube的位置
    public GameObject prefab;
    void Start()
    {
        nowTimer = timer;//开始时初始化时间
    }

    void Update()
    {
        timer += Time.deltaTime;
        if (timer - nowTimer >= 1)//每隔一秒时间移动一个单位
        {
            nowTimer = timer;//移动之后把时间赋给当前时间
            oldPos = transform.position;//记录位置
            transform.Translate(Vector3.forward);//移动
            //follew.transform.position = oldPos;
            if (next)
            {
                next.Move(oldPos);
            }
        }
        float h = Input.GetAxis("Horizontal");
        if (h > 0)
        {
            transform.Rotate(Vector3.up * 90f);
        }
        if (h < 0)
        {
            transform.Rotate(Vector3.up * -90f);
        }
        if (Input.GetMouseButtonDown(0))//单击调用实例化预设体的方法
        {
            AddCube();
        }
    }
    void AddCube()
    {
        GameObject go = Instantiate(prefab, new Vector3(100, 100, 100), Quaternion.identity) as GameObject;
        if (!next)
        {
            next = go.GetComponent<FollowCube >();
            tail = next;
        }
        else
        {
            tail.son = go.GetComponent<FollowCube >();//创建了连接
            tail = tail.son;
        }
    }
}

绿色预设体Cube挂载的脚本代码:

using UnityEngine;
using System.Collections;
public class FollowCube : MonoBehaviour
{
    Vector3 pos;
    public FollowCube son;
    public void Move(Vector3 target)
    {
        //先记录下原来的位置
        pos = transform.position;
        //再离开原来位置
        transform.position = target;
        //最后通知小弟移动到pos这个位置
        if (son != null)
        {
            son.Move(pos);
        }
    }
}

刚开始写这样的博客,把自己做的代码开源分享给大家,有不解的地方可以联系我,我也会再接再厉的。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值