c# - 到达终点时如何将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;
}
}
}
解决方案
问题是该.Translate
方法通过特定向量移动对象。它没有分配固定位置。
如果要重置z
变换的位置,请将新向量分配给.position
包含原始值x
和y
值的属性,并将 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);
}
}
}
推荐阅读
- javascript - 为什么在这里使用解构赋值?它到底在做什么?
- swift - 使用 UIDocumentPickerViewController 选择 Google 文档
- java - DB2:用户定义的函数或过程无法映射到单个 Java 方法
- c# - 谷歌链接在asp.net中进入错误屏幕,如何重定向到主页?
- ruby-on-rails - 在heroku上安装pdf2htmlEX
- laravel - 获取没有依赖的作曲家学说包
- python - 使用不同目录中文件的 Python 脚本
- c - 在 C 程序中,计算 NxM 数组中数字 0 到 9 的出现次数。我的计数数字而不是单个数字计数?
- c# - C# JSON 反序列化为局部变量
- css - 只有少数 CSS 文件在 React 中应用它们的样式