我试图让我的物体向上移动,但是在一个随机的锯齿形方向上。我使用以下代码让我的对象向上移动。
transform.position += transform.up * playerspeed * Time.deltaTime;
但是,我如何使这个物体向上移动,但是在我的最小值和最大值的Z字形方向上。当它重生时,锯齿形的路径是随机的?
答案 0 :(得分:1)
您需要做的就是选择一个x位置,然后在向上移动时移动它。然后当你到达它时,只需重复这个过程。
试试这个:
private float minBoundaryX = -3f;
private float maxBoundaryX = 3f;
private float targetX;
private float horSpeed = 3f;
private float vertSpeed = 2f;
//Pick a random position within our boundaries
private void RollTargetX()
{
targetX = Random.Range(minBoundaryX, maxBoundaryX);
}
//Calculate the distance between the object and the x position we picked
private float GetDistanceToTargetX()
{
return Mathf.Abs(targetX - transform.position.x);
}
private void Update()
{
//Roll a new target x if the distance between the player and the target is small enough
if (GetDistanceToTargetX() < 0.1f)
RollTargetX();
//Get the direction (-1 or 1, left or right) to the target x position
float xDirection = Mathf.Sign(targetX - transform.position.x);
//Calculate the amount to move towards the x position
float xMovement = xDirection * Mathf.Min(horSpeed * Time.deltaTime, GetDistanceToTargetX());
transform.position += new Vector3(xMovement, vertSpeed * Time.deltaTime);
}