【问题标题】:move object upwards but in a random min max value向上移动对象但随机最小最大值
【发布时间】:2017-04-13 19:16:05
【问题描述】:

我正试图让我的对象向上移动,但方向是随机的之字形。我使用以下代码让我的对象向上移动。

transform.position += transform.up * playerspeed *  Time.deltaTime;

但是,我如何使这个对象向上移动,但以我自己的最小值和最大值以之字形方向移动。而当它重生时,之字形的路径是随机的?

【问题讨论】:

  • 你能画出你想要达到的路径的图像吗?您是否只是想为对象添加横向运动,并在两个值之间振荡?之字形的每一步都是随机长度吗?每个部分的角度应该相同,还是也可以变化? (同样,视觉辅助可能会含蓄地回答所有这些问题。)

标签: c# unity3d


【解决方案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);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-13
    • 1970-01-01
    • 2020-09-02
    • 2015-05-07
    • 2018-04-09
    相关资源
    最近更新 更多