簡體   English   中英

將游戲對象移動到其他游戲對象的上一個位置

[英]Move a GameObject to the previous position of other GameObject

我正在嘗試實現類似於經典蛇游戲的東西,但是,玩家每次按下按鈕時只移動一個單位,並且“尾巴(藍色方塊)”需要移動到頭部的先前位置

在此處輸入圖像描述

我希望藍色方塊始終停留在白色方塊的最后一個位置,而不是在它上面。

這是我的代碼:

[SerializeField] Transform segmentPrefab;

Vector2 moveInput;
Vector2 currentHeadPos;

//I want to add more segments to the tail so I created a list
List<Transform> segmentList;

void Start()
{
    //I add the head as the first object of the list
    segmentList = new List<Transform>();
    segmentList.Add(transform);
}

void OnMove(InputValue input)
{
    //I tried/expected to save the head Pos here and use it to move the segment with this
    currentHeadPos = transform.position;

    moveInput = input.Get<Vector2>();


    //Horizontal movement
    if (moveInput.x != 0)
    {
        transform.position = new Vector2(transform.position.x + moveInput.x, transform.position.y);
    }

    //Vertical movement
    if (moveInput.y != 0)
    {
        transform.position = new Vector2(transform.position.x, transform.position.y + moveInput.y);
    }

    //I loop through the list and move the last item to the position in front of it
    for (int i = segmentList[segmentList.Count - 1; i > 0, i --]
    {
      segmentList[i].position = segmentList[i - 1].position;
    }

   
}


//This works fine, is to add new objects to the list
void Connect()
{
    Vector3 offset = new Vector3(-1, 0f, 0f);
    Transform newSegment = Instantiate(segmentPrefab);
    newSegment.position = segmentList[segmentList.Count - 1].position + offset;
    segmentList.Add(newSegment);
}

private void OnTriggerExit2D(Collider2D collision)
{
    if (collision.CompareTag("Conector"))
    {
        Connect();
    }
}

我對統一和編碼相當陌生,我不知道如何避免藍色方塊在每次移動時都在它的頂部結束

我將假設 segmentList[0] 處的段是你的白色方塊,而列表下方的所有段都是你的藍色方塊。

以下代碼行正在移動您在 segmentList[0] 中找到的轉換:

    //Horizontal movement
    if (moveInput.x != 0)
    {
        transform.position = new Vector2(transform.position.x + moveInput.x, transform.position.y);
    }

    //Vertical movement
    if (moveInput.y != 0)
    {
        transform.position = new Vector2(transform.position.x, transform.position.y + moveInput.y);
    }

如果您在 segmentList[0] 處的變換已經移動,那么當您更新segmentList[1] = segmentList[0].position時,您已經更新了 segmentList[0],因此它實際上是當前位置。

如果您在OnMove方法中將以下代碼移到前面,您應該會得到預期的結果:

    //I loop through the list and move the last item to the position in front of it
    for (int i = segmentList[segmentList.Count - 1; i > 0, i --]
    {
      segmentList[i].position = segmentList[i - 1].position;
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM