MoveTowards problem

Hey everyone. I’m working on a main menu, and i’m trying to get it to move back and forth when you click certain buttons. When I click options and it moves to the options area, but when I try to hit back (They are both run under the same script), it stays put and doesn’t move back.

Here is the script i’m using:

var Selectsound : AudioClip;
var HoverSound : AudioClip;
var target: Transform;
var speed: float;
var Select : boolean = false;

function OnMouseEnter () {
       audio.PlayOneShot(HoverSound, 0.7);
      transform.renderer.material.color = Color.gray;
    }
    
    function OnMouseExit () {
      transform.renderer.material.color = Color.white;
    }
    
        function OnMouseDown () {
        Select = true;
      transform.renderer.material.color = Color.cyan;
      audio.clip = Selectsound;
       audio.Play();
    }
    
    function Update () {
                   if(Select == true){
      var step = speed * Time.deltaTime;
       Camera.mainCamera.transform.position = Vector3.MoveTowards(Camera.mainCamera.transform.position, target.position, step);
    }
    }

1 Answer

1

It looks to me like you only ever tell the object to move to one place. You’re going to need to know which state it is in; position1, position2 (and possibly moving as well). If the menu is in position1 then you need to set the target to the position of position2. Make sense?

1 > 2
2 > 1

Another way to think of the problem is to cache the initial position of the menu and move to a position defined by it’s Select state.

var startingPosition : Vector3;

function Awake()
{
    startingPosition = transform.position;
}

function OnMouseDown()
{
    MoveMenu(Select);
    Select = !Select;
}

function MoveMenu(direction : bool)
{
    Vector3 pos = (direction ? target.position : startingPosition);
    do
    {
        Camera.mainCamera.transform.position =
        Vector3.MoveTowards(Camera.mainCamera.transform.position,
        pos, step);
        moving = !(transform.position == pos);
        yield return null;
    } while (moving)
}