首页 > 解决方案 > 到达终点时如何将z位置重置为0?

问题描述

我让我的对象向一个方向移动,并在它到达位置 10 时将 z 位置重置为 0。但是当位置 z 到达 10 时,它不会返回到 0。

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



public class NewBehaviourScript : MonoBehaviour
{
    float z = 1.0F;
   void Update()
    {
        
        if (z < 10.0f)
        {
            //move object forward
            transform.Translate(0,0,z * Time.deltaTime * 0.5F);
        }
        else
        {
            z = 0;
        }
    }
}

标签: c#unity3d

解决方案


问题是该.Translate方法通过特定向量移动对象。它没有分配固定位置。

如果要重置z变换的位置,请将新向量分配给.position包含原始值xy值的属性,并将 a0作为最后一个参数。

这是您的代码的固定版本:

using UnityEngine;

public class NewBehaviourScript : MonoBehaviour
{
    private const float Speed = 1.0f;

    private void Update()
    {
        if (transform.position.z < 10.0f)
        {
            // Moving object forward
            transform.Translate(0, 0, Speed * Time.deltaTime);
        }
        else
        {
            transform.position = new Vector3(
                transform.position.x,
                transform.position.y,
                0f);
        }
    }
}

推荐阅读