[Solved] Move objects at constant speed on click

Hi guys,

I’m designing a welcome screen to my game and I want the GameObjects to move out from screen at a constant speed with a simple click:
5807611--614341--upload_2020-5-5_19-9-12.png
So, what I want is to click anywhere in the screen and move the cogs at a constant speed to make them disappear from screen. Here’s my script attempt:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class StartScreen: MonoBehaviour
{
   
    public GameObject leftCog1;
    public GameObject leftCog2;
    public GameObject rightCog1;
    public GameObject rightCog2;
    public GameObject welcomText;
   
   
    public void Update(){
        float speedleft = -1;
        float speedright = 1;
        if(Input.GetKey(KeyCode.Mouse0)){
            leftCog1.transform.Translate (speedleft,0,0);
            leftCog2.transform.Translate (speedleft,0,0);
            rightCog1.transform.Translate (speedright,0,0);
            rightCog2.transform.Translate (speedright,0,0);
        }
    }
   

}

It works as long as I keep pressed the left mouse button, but I want this to happen “forever”. If I know how to do this, then I will be able to tune up the code, but I need to move these cogs at a constant speed with just one click.

Any hints?

Thanks!

so the problem you have here is that you are only calling the move once, a simple way to fix this is create a bool called anything you want then set it to false in the start menu then when clicked set it to true. Below that in the update function make a statement that says if your bool is true then move the objects so it would look like this

using System.Collections.Generic;
using UnityEngine;
public class StartScreen: MonoBehaviour
{
public bool isClicked;
public GameObject leftCog1;
public GameObject leftCog2;
public GameObject rightCog1;
public GameObject rightCog2;
public GameObject welcomText;

public void Start()
{
isClicked = false;
}
public void Update(){
float speedleft = -1;
float speedright = 1;
if(Input.GetKey(KeyCode.Mouse0))
{
isClicked = true;
}
if(isClicked == true)
{
leftCog1.transform.Translate (speedleft,0,0);
leftCog2.transform.Translate (speedleft,0,0);
rightCog1.transform.Translate (speedright,0,0);
rightCog2.transform.Translate (speedright,0,0);
}
}
}

1 Like

That was brilliant. It works like a charm. Thank you so much!