- Home /
move a button On click - rather than on game start
I have a button that moves in from right to its target position - script below. What I tried and couldn’t do is to: Move the button in when I click on a button (another button) rather than on start. How should I go about doing that?
var target = 100.0;
var move = 200;
function Update () {
move = Mathf.Lerp(target + 100, target , Time.time);
}
function OnGUI () {
GUI.Button(Rect(move, 100.0, 100.0, 50.0), "Moving Button!");
}
Answer by Zarenityx · Jan 18, 2013 at 03:33 PM
Assuming you want to keep your move calculations in your Update() function, try this:
var target = 100.0;
var move = 200;
private var moving : boolean = false;
private var clicktime : float;
function Update () {
if(moving){
move = Mathf.Lerp(target + 100, target , Time.time-clicktime);
}
}
function OnGUI () {
if(GUI.Button(Rect(//where you want the other button), "Make the button move!") && !moving){
clicktime = time.time;
moving = true;
}
GUI.Button(Rect(move, 100.0, 100.0, 50.0), "Moving Button!");
}
You will need to change the '//where you want the other button' to a real rect, of course.
I wish it worked - it just jumps to the end position. the lerp still calculates the distance if i click the button or not. I mean - if you click the button immediately after you hit play , the button moves. But if you click the button after waiting for a second the button it jumps strait to the end. and i don't $$anonymous$$d if it not in the update() function as long as it works. tnx
Try it now (I edited it). I think the problem was this: When you press the button immediately, Time.time still is 0. But afterwards, Time.time>0, and therefore farther ahead in the Lerp. Here, I found the time when you pressed the button, and subtracted it from the current time to get the time since it was clicked. I also added "&& !moving". This keeps it from jumping back to the beginning again after you push it.
Nice! it works like a charm! i wouldn't have come up with that :) Thank you zare' .I appreciate it a lot!