Search Unity

How can I used OnMouseDown like a switch button one click to move forward another to move back ?

Discussion in 'Scripting' started by DubiDuboni, Sep 5, 2019.

  1. DubiDuboni

    DubiDuboni

    Joined:
    Feb 5, 2019
    Posts:
    131
    Code (csharp):
    1.  
    2. using System.Collections;
    3. using System.Collections.Generic;
    4. using UnityEngine;
    5.  
    6. public class VideoSettings : MonoBehaviour
    7. {
    8.     public MeshRenderer VideoAudioCube;
    9.     public float speed = 5f;
    10.     public float distanceToMove;
    11.  
    12.     private bool keepMoving = true;
    13.     private Vector3 startPos;
    14.     private Vector3 endPos;
    15.  
    16.     private void Start()
    17.     {
    18.         startPos = VideoAudioCube.transform.position;
    19.     }
    20.  
    21.     private void OnMouseDown()
    22.     {
    23.         if (keepMoving == true)
    24.         {
    25.             keepMoving = false;
    26.             if (transform.GetComponentInChildren<TextMesh>().text == "Video")
    27.             {
    28.                 StartCoroutine(MoveVideo());
    29.             }
    30.         }
    31.     }
    32.  
    33.     private IEnumerator MoveVideo()
    34.     {
    35.         endPos = VideoAudioCube.transform.position + Vector3.right * distanceToMove;
    36.  
    37.         VideoAudioCube.enabled = true;
    38.  
    39.         while (VideoAudioCube.transform.position != endPos)
    40.         {
    41.             VideoAudioCube.transform.position =
    42.                 Vector3.MoveTowards(VideoAudioCube.transform.position, endPos, Time.deltaTime * speed);
    43.             yield return null;
    44.         }
    45.     }
    46. }
    47.  
    When I click with the mouse on the object the object move one to some distance.
    Now I want to do that another click will move the object back to it's startPos so the OnMouseDown will be like a switch button. Each click will move it to the other direction endPos and startPos.
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,742
    Just keep track of a bool that is back/forth essentially, and when you click, decide which way to move, then invert the bool from true back to false, and vice versa.
     
    DubiDuboni likes this.