user2962748
user2962748

Reputation: 11

move object upwards but in a random min max value

I'm trying to get my object to move upwards but in a random zig zag direction. i have used the following code to get my object to move upwards.

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

However how do i go about making this object move upwards but in a zigzag direction with my own minimum and maximum values. and when it respawns the pathway of the zigzag is random?

Upvotes: 0

Views: 171

Answers (1)

CaTs
CaTs

Reputation: 1323

All you need to do is pick an x position and then move to it as you are moving upwards. Then when you reach it, just repeat the process.

Try this out:

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);
}

Upvotes: 1

Related Questions