1
\$\begingroup\$

I am making a puzzle game in Unity. I have several GameObjects that have children objects where each child object has a BoxCollider2D.

The game requires that the pieces be rotated, but to position them correctly, they also need to be translated under certain rotations. I thought a good way to handle this would be using an animator that has 0, 90, 180 and 270 degree states. When the objects are by themselves, I have this working correctly.

The problem I am having is when there are two adjacent GameObjects. When the user tries to rotate a block and the rotation would result in overlapping colliders, I want to ignore the rotate command and do nothing. Traditionally, this would mean that I would rotate the piece, check collisions, and if there is a collision, rotate back in the same Update() call.

My question is: Is there any way after telling the animation to rotate i.e.

animator.SetFloat("Rotation",animator.GetFloat("Rotation") + 90);

to subsequently tell it to jump to the last frame of the new animation state so that I can check collisions on it and then revert the animation to its original position if there is a collision -- all in the Update() function?

Or am I better off ditching the Animator and doing it myself?

\$\endgroup\$
  • \$\begingroup\$ In my opinion ditch this approach. It's never a good idea to to physics checks based on animations. \$\endgroup\$ – Uri Popov Jun 10 '16 at 15:02
0
\$\begingroup\$

You should not have your logic be done in the animator. You need to do your calculations in the code behind, and then you can call on the animator when you know what you want animated. You may want to look into adapting the MVC pattern for unity.

If you really want to do it like this though, you can add an event to a key frame in Unity animations. This event will call a method, where you can perform a check. Then in that check, you can either stop your animation, play it in reverse, or let it play through.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.