我在Unity3D中编写了此代码,该代码应将对象旋转一圈,是这种情况,只是不考虑起始位置。 我不明白为什么职位不考虑开始写的功能
public class RotationCircuit : MonoBehaviour
{
float timeCounter = 0;
float speed;
float width;
float height;
private float startPosY;
private float startPosX;
private float startPosZ;
void Start()
{
speed = 1;
width = 4; //largueur
//height = 1; //hauteur
startPosX = transform.position.x;
startPosY = transform.position.y;
startPosZ = transform.position.z;
float y = GetComponent<Transform>().position.y;
float x = GetComponent<Transform>().position.x;
float z2 = GetComponent<Transform>().position.z;
transform.position = new Vector3(x, y, z2);
}
void Update()
{
timeCounter += Time.deltaTime * speed;
float x2 = Mathf.Cos(timeCounter) * width;
//float y2 = Mathf.Sin(timeCounter) * height; //utile pour faire des haut et bas
float y2 = GetComponent<Transform>().position.y;
float z2 = GetComponent<Transform>().position.z;
transform.position = new Vector3(x2, y2, z2);
}
}
答案 0 :(得分:3)
通常,您应该使用transform.position
而不是GetComponent<Transform>().position
然后您的代码块
float y = transform.position.y;
float x = transform.position.x;
float z2 = transform.position.z;
transform.position = new Vector3(x, y, z2);
绝对没有任何改变...您将获得当前位置,将其存储在局部变量中并写回完全相同的位置...
它们还具有与您已经存储的相同的值
startPosX = transform.position.x;
startPosY = transform.position.y;
startPosZ = transform.position.z;
后来您再也不会使用这些值了。
Update
float x2 = Mathf.Cos(timeCounter) * width;
float y2 = transform.position.y;
float z2 = transform.position.z;
transform.position = new Vector3(x2, y2, z2);
仅更改通过以下方式计算的头寸的x
分量
Mathf.Cos(timeCounter) * width;
在任何时候都不会考虑首字母transform.position.x
或startPosX
。
我不完全知道您想如何考虑起始位置,但看起来像这样:
// Little hint: By making those fields serialized
// you can adjust those values directly in the Inspector
// especially while running the Game without having to recompile everytime
[SerializedField] private float speed = 1;
[SerializedField] private float width = 4;
[SerializedField] private float height = 1;
private float timeCounter = 0;
private Vector3 startPosition;
private void Start()
{
// you can simply store the Vector3 position
// no need to store each component individually
startPosition = transform.position;
}
private void Update()
{
timeCounter += Time.deltaTime * speed;
var x = Mathf.Cos(timeCounter) * width;
var y = Mathf.Sin(timeCounter) * height;
// from the startPosition move x right and y up
transform.position = startPosition + Vector3.right * x + Vector3.up * y;
}
开头的对象跳一次,即width
向右跳一次,显然与Mathf.Cos
相对,1
在开始时间0
上。