khmer2040
khmer2040

Reputation: 157

Unity3D - object moving up and down continuously within a y-axis range

I have a target that moves up and down, but I'm not sure how to limit it's vertical movement to a certain y-axis range. Thanks for any advice. Code is as follows:

using UnityEngine;
using System.Collections;

public class TargetMovementVertical : MonoBehaviour 
{
    public int maxSpeed;

    private Vector3 startPosition;

    // Use this for initialization
    void Start () 
    {
        maxSpeed = 3;

        startPosition = transform.position;
    }

    // Update is called once per frame
    void Update ()
    {
        MoveVertical ();
    }

    void MoveVertical()
    {
        transform.position = new Vector3(transform.position.x, startPosition.y + Mathf.Sin(Time.time * maxSpeed), transform.position.z);

        if(transform.position.y > 1.0f)
        {
            transform.position = new Vector3(transform.position.x, transform.position.y, transform.position.z);
        }
        else if(transform.position.y < -1.0f)
        {
            transform.position = new Vector3(transform.position.x, transform.position.y, transform.position.z);
        }
    }
}

Upvotes: 2

Views: 14537

Answers (2)

Mudabbir Ali
Mudabbir Ali

Reputation: 21

private Vector3 startPosition;
bool up=true;
// Use this for initialization
void Start () 
{
    //maxSpeed = 3;
    startPosition = transform.position;
}
// Update is called once per frame
void Update ()
{
    MoveVertical ();
}
void MoveVertical()
{   
    var temp=transform.position;
    print (up);
    if(up==true)
    {
        temp.y += 0.01f;
        transform.position=temp;
        if(transform.position.y>=0.39f)
        {
            up = false;
        }
    }
    if(up==false)
    {
        temp.y -= 0.01f;
        transform.position=temp;
        if(transform.position.y<=0.14f)
        {
            up = true;
        }
    }
}

Adjust your values according to your need.

Upvotes: 2

Mohanad S. Hamed
Mohanad S. Hamed

Reputation: 301

Your question may have two meanings:

1- If you want to limit y shifting to be within -1 to 1, use the following code: (e.g. if your original y equals 5, the result will be within range (4,6)

transform.position = new Vector3(0, startPosition.y + Mathf.Sin(Time.time * maxSpeed), 0);

2- If you want to make y value always within -1 to 1, use the following code: (your result y value will be within range (-1,1) regardless of original y value)

transform.position = new Vector3(transform.position.x, Mathf.Sin(Time.time * maxSpeed), transform.position.z);

Upvotes: 4

Related Questions