我有一个代码可以使多维数据集在其原始放置位置的一定范围内来回移动。
脚本直接在立方体上,并且确实在移动,但是围绕0,0,0坐标,而不是其原始位置。
这是我的代码:
using UnityEngine;
public class ObstacleResonator : MonoBehaviour
{
public float xspeed = 0f;
public float yspeed = 0f;
public float zspeed = 0f;
public float xrange = 0f;
public float yrange = 0f;
public float zrange = 0f;
float StartX;
float StartY;
float StartZ;
Vector3 desiredPosition;
void Start()
{
// this is what i think is the problem, the variables are not getting assigned
float StartX = transform.position.x;
float StartY = transform.position.y;
float StartZ = transform.position.z;
}
// Update is called once per frame
void Update()
{
// the following is to make it reverse once it is out of range in any of the axes
if (transform.position.x > xrange + StartX)
{
xspeed = -xspeed;
}
if (transform.position.x < -xrange + StartX)
{
xspeed = -xspeed;
}
if (transform.position.y > yrange + StartY)
{
yspeed = -yspeed;
}
if (transform.position.y < -yrange + StartY)
{
yspeed = -yspeed;
}
if (transform.position.z > zrange + StartZ)
{
zspeed = -zspeed;
}
if (transform.position.z < -zrange + StartZ)
{
zspeed = -zspeed;
}
// the following actually moves the cube
desiredPosition.x = transform.position.x + xspeed * Time.deltaTime;
desiredPosition.y = transform.position.y + yspeed * Time.deltaTime;
desiredPosition.z = transform.position.z + zspeed * Time.deltaTime;
transform.position = desiredPosition;
}
}
可能有一种更紧凑的编写方法。
立方体在0,0,0周围移动,而不是其原始变换位置。我尝试手动分配StartX,StartY,StartZ值,并且效果很好,但是它们似乎并没有在开始时被分配。
问题是您在Start()函数中声明了NEW变量,一旦执行该函数,它们就会超出范围。您不更新类变量。
改用它:
void Start()
{
StartX = transform.position.x;
StartY = transform.position.y;
StartZ = transform.position.z;
}