Sena
Sena

Reputation: 298

How to stop a method after it done in Update() function? - C# - Unity3D

Recently I'm making a chess game which has animation when the chess move. I used two method, RotateTowards and Translate(). RotateTowards() only run in Update() function. Here is my code:

using UnityEngine;
using System.Collections;

public class OnTouch : MonoBehaviour {

    public GameObject cube;
    public GameObject sphere;
    int clicked;
    Quaternion lastRot;

    // Use this for initialization
    void Start () {
        clicked = 0;
    }

    // Update is called once per frame
    void Update () {
    if(clicked == 1)
        {
            var rotation = Quaternion.LookRotation(cube.transform.position - transform.position);
            print(rotation);
            rotation.x = 0;
            rotation.z = 0;
            cube.transform.rotation = Quaternion.RotateTowards(cube.transform.rotation, rotation, 100 * Time.deltaTime);
            if(cube.transform.rotation = ???? <- No Idea){

                clicked = 0;
            }
        }
    }

    void OnMouseDown()
    {
        print("clicked");
        clicked = 1;
    }
}

I attach that code to all chess tile. So, after the cube stop rotating, I tried to click another tile. But, the previous RotateTowards() method keep running, so it ran both. I've try to make IF logic, but I have no idea for

if(cube.transform.rotation == ??? <-- No idea){

clicked = 0;

}

Any solution? Thank you!

Upvotes: 3

Views: 615

Answers (2)

Milad Qasemi
Milad Qasemi

Reputation: 3049

it will never reaches your final rotation, it will get very close though so you can check if the angle between your destination rotation and current rotation is smaller than a small degree then you can say it reached.

    float DestAngle = 1.0f; //here we take 1 degree as the near enough angle
    float angle = Quaternion.Angle(transform.rotation, target.rotation);//we calculate the angle between current rotaion and destination
    if (Mathf.Abs (angle) <= DestAngle ) { //we reached }

Upvotes: 1

SilentSin
SilentSin

Reputation: 1036

if (cube.transform.rotation == rotation)

Upvotes: 1

Related Questions