You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Unity贪吃蛇开发疑问:蛇身节点无法跟随头部移动的原因

Unity贪吃蛇蛇身跟随异常问题分析请求

我刚接触Unity,正在开发一款贪吃蛇游戏,设计的蛇身跟随逻辑如下:

  • 头部标记自身当前位置
  • 头部向目标方向移动
  • 进入循环:每个子节点移动到上一个标记的位置,然后将该子节点原来的位置设为新的标记位置

按这个逻辑蛇身应该依次跟随头部移动,但实际运行后蛇身出现了异常形状(附[初始位置截图]、[按W键后的位置截图])。

以下是我的Movement脚本代码:

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

public class Movement : MonoBehaviour
{
    int fps = 60;
    Vector3 prev_pos, mark_pos;
    void Start()
    {
        Application.targetFrameRate = fps;
    }

    void Update_child()
    {
        foreach(Transform child in transform)
        {
            prev_pos = child.position;
            child.position = mark_pos;
            mark_pos = prev_pos;
            print(child.position);
            print(child.name);
        }   
    }

    void Update()
    {
        mark_pos = transform.position;
        if (Input.GetKeyDown("w"))  
        {
            transform.position += new Vector3(0, 1, 0);
            Update_child();
        }
        else if (Input.GetKeyDown("a"))
        {
            transform.position += new Vector3(-1, 0, 0);
            Update_child();
        }
        else if (Input.GetKeyDown("s"))
        {
            transform.position += new Vector3(0, -1, 0);
            Update_child();
        }
        else if (Input.GetKeyDown("d"))
        {
            transform.position += new Vector3(1, 0, 0);
            Update_child();
        }
    }
}

我希望先搞清楚错误的根本原因,而不是直接拿到修复后的代码,恳请帮忙分析问题所在。我已经尝试过使用相对位置和绝对位置,但都没有解决问题。

内容的提问来源于stack exchange,提问作者Fantastish

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 16:15:51