Unity 制作蛇形移动的效果

本文介绍了一个Unity脚本,通过该脚本可以控制物体进行摆动。脚本使用协程来平滑地改变物体的位置,实现从一个位置移动到另一个位置的效果。当按下Q键时,物体开始摆动,再次按下则停止摆动并回到原位。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

效果:
在这里插入图片描述

新建脚本,代码如下:

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

public class Test : MonoBehaviour
{
    public List<Transform> brick;
    Coroutine[] temp;
    public float range = 10;//摆动范围
    private void Start()
    {
        temp = new Coroutine[brick.Count];
    }

    private void Update()
    {
        if (Input.GetKeyDown(KeyCode.Q))
        {
            //StopAllCoroutines();
            if (temp[0] != null)
                StopCoroutine(temp[0]);
            temp[0] = StartCoroutine(FirstMove(range));
        }
        if (Input.GetKeyUp(KeyCode.Q))
        {
            //StopAllCoroutines();
            if (temp[0] != null)
                StopCoroutine(temp[0]);
            temp[0] = StartCoroutine(FirstMove(0));
        }
    }

    IEnumerator FirstMove(float moveTo)
    {
        if (temp[1] != null)
            StopCoroutine(temp[1]);
        temp[1] = StartCoroutine(Follow(1, moveTo));
        float speed = 0.1f;
        while (Mathf.Abs(brick[0].position.x - moveTo) > 0.01)
        {
            Vector3 temp = brick[0].position;
            temp.x = Mathf.Lerp(temp.x, moveTo, speed);
            brick[0].position = temp;
            speed += Time.deltaTime;
            yield return null;
        }
        Vector3 temp1 = brick[0].position;
        temp1.x = moveTo;
        brick[0].position = temp1;
    }


    IEnumerator Follow(int i, float moveTo)
    {
        yield return new WaitForSeconds(0.05f);
        float speed = 0.1f;
        if (i < brick.Count - 1)
        {
            if (temp[i + 1] != null)
                StopCoroutine(temp[i + 1]);
            temp[i + 1] = StartCoroutine(Follow(i + 1, moveTo));
        }
        while (Mathf.Abs(brick[i].position.x - moveTo) > 0.05)
        {
            Vector3 temp = brick[i].position;
            temp.x = Mathf.Lerp(temp.x, moveTo, speed);
            brick[i].position = temp;
            speed += Time.deltaTime;
            yield return null;
        }
        Vector3 temp1 = brick[i].position;
        temp1.x = moveTo;
        brick[i].position = temp1;
        temp[i] = null;
    }
}

创建很多个cube出来(当然你可以选择其他模型来替代),拖到挂载了那个脚本的brick就行了,按下Q键就开始摆动。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值