Summary
I am currently making a small game of match the pairs in Unity. To create the ‘cards’ I used 2 planes and put them back to back and grouped them in an empty object called Card. I created a prefab from this and duplicated them with an ID with them for example: Card1, Card2, Card3 etc.
In the CardScript.cs file which is attached as a component on every prefab is responsible for the movement of these cards. I started the scene by showing the player the cards (front side up) and then turn 190 degrees after a delay. When the player hovers over the cards, the card’s material tint changes colour and when the player moves the cursor somewhere else, the card changes the material tint back to normal.
Problem
I want the card to turn to the front side up by clicking on it so I used the OnMouseDown() method in Unity. This is currently my code in the Update() method:
void Update()
{
if (startCheck)
{
transform.rotation = Quaternion.RotateTowards(transform.rotation, beginRotation, flipSpeed * Time.deltaTime); //used for start sequence
}
if (mouseEnter)
{
Transform child = gameObject.transform.FindChild("CardBack");
child.GetComponent<Renderer>().material.color = Color.Lerp(child.GetComponent<Renderer>().material.color, Color.red, hoverOverSpeed * Time.deltaTime);
if (clicked)
{
transform.rotation = Quaternion.RotateTowards(transform.rotation, beginRotation, flipSpeed * Time.deltaTime);
}
}
else
{
Transform child = gameObject.transform.FindChild("CardBack");
child.GetComponent<Renderer>().material.color = Color.Lerp(child.GetComponent<Renderer>().material.color, Color.white, hoverOverSpeed * Time.deltaTime);
}
}
However, whenever I press a card after the starting rotation, nothing happens. I have tried multiple other ways even by trying to make the rotation immediate by using for example transform.Rotate but still, nothing worked. But, I know it is something I’m doing wrong because I did a Debug.Log in the ‘if (clicked)’ statement instead of the attempt of rotating the card and the Debug.Log worked. Can anyone tell me what I am doing wrong and how to fix it? Also, I only recently delved into Unity like this so I appreciate if people simplify things for me too. ![]()
P.S. I also hope I posted this correctly since this is my first question so sorry if I did this wrong!
Key
- startCheck is a boolean which is only set to true after the delay. This causes the cards to do the flip animation in the beginning (after the delay).
- beginRotation is a Quaternion used to make the cards flip properly by making them turn Vector3.forward for 180 degrees.
- flipSpeed is self-explanatory.
- mouseEnter is a boolean which is set to true after the user hovers the cursor over a card and is set to false whenever he moves the cursor somewhere away from the card.
- clicked is a boolean which is set to true after the player presses on a card.