В моем подходе, когда я создаю создание нового сегмента тела змеи, я даю ему ссылку на сегмент, который был порожден перед ним, используя ссылку, я получаю доступ к ранее порожденным сегментам Известный преобразование. Предоставление и переместите новую часть тела там. Для некоторого Редсона вместо того, чтобы двигаться один за другим, все сегемтские тела сразу же следуют за части змеиной головки. Это означает, что все сегменты тела устанавливают свою позицию в последнюю позицию змеиной головы. < /P>
Скрипт головки змеи: < /p>
Код: Выделить всё
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEditor;
using UnityEngine;
public class snakeHeadController : MonoBehaviour
{
private string directionOfMovement;
private float timer;
public float delay = 0;
public float movementIncrement = 1;
public Vector3 lastPosition;
public GameObject snakeBodyPart;
GameObject newBodyPart;
public GameObject lastCreatedBodyPart;
int bodyPartNumber = 0;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
changeDirectionOfSnake();
moveHead(directionOfMovement);
}
void moveHead(string directionOfMovement)
{
timer += Time.deltaTime;
if (timer > delay)
{
lastPosition = transform.position;
if (directionOfMovement == "Right")
{
transform.position += new Vector3(movementIncrement, 0, 0);
}
else if (directionOfMovement == "Left")
{
transform.position += new Vector3(-movementIncrement, 0, 0);
}
else if (directionOfMovement == "Up")
{
transform.position += new Vector3(0, movementIncrement, 0);
}
else if (directionOfMovement == "Down")
{
transform.position += new Vector3(0, -movementIncrement, 0);
}
timer -= delay;
}
}
//function for determening direction of movement of the head
void changeDirectionOfSnake()
{
if (Input.GetKeyDown(KeyCode.D) && directionOfMovement != "Left")
{
directionOfMovement = "Right";
} else if(Input.GetKeyDown(KeyCode.A) && directionOfMovement != "Right")
{
directionOfMovement = "Left";
} else if( Input.GetKeyDown(KeyCode.W) && directionOfMovement != "Down")
{
directionOfMovement = "Up";
} else if (Input.GetKeyDown(KeyCode.S) && directionOfMovement != "Up")
{
directionOfMovement = "Down";
}
}
//this function spawns a new body segment and passes a reference of the last created body segment to the newly created one
public void spawnBodyPart()
{
newBodyPart = Instantiate(snakeBodyPart, transform);
newBodyPart.name = "snakeBodySegment" + bodyPartNumber.ToString();
if (lastCreatedBodyPart != null)
{
newBodyPart.GetComponent().getReferenceToBodyBeforeMe(lastCreatedBodyPart);
}
bodyPartNumber++;
lastCreatedBodyPart = newBodyPart;
}
}
< /code>
part part (сегмент) Скрипт: < /p>
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class snakeBodyScript : MonoBehaviour
{
private GameObject head;
private snakeHeadController headScript;
public GameObject bodyBeforeMe;
public Vector3 myLastPostion;
// Start is called before the first frame update
void Start()
{
head = GameObject.Find("snakeHead");
headScript = head.GetComponent();
}
// Update is called once per frame
void LateUpdate()
{
moveBody();
}
void moveBody()
{
if (bodyBeforeMe == null)
{
myLastPostion = transform.position;
transform.position = headScript.lastPosition;
}
else
{
myLastPostion = transform.position;
transform.position = bodyBeforeMe.GetComponent().myLastPostion;
}
}
public void getReferenceToBodyBeforeMe(GameObject bodyPart)
{
bodyBeforeMe = bodyPart;
}
}
На мой взгляд, решение, которое я реализовал, кажется, что оно должно работать, хотя оно запутано с помощью передачи ссылок и всего, что (я уверен, что есть более элегантный) способ сделать это, но я просто не могу, похоже понять, почему мой подход не работает.
Подробнее здесь: https://stackoverflow.com/questions/793 ... s-in-unity
Мобильная версия