# Question Rotating a cube in multiple directions (forward, back, left, right) not working in a sequence

Discussion in 'Getting Started' started by szmark16, Apr 18, 2024.

1. ### szmark16

Joined:
Feb 29, 2020
Posts:
1
Hey!
I have a project with artificial inteligence for my university. The problem basically looks like a 3d grid with some walls a goal and a moveable cube. The cube moves around the grid by rotating in the direction of the movement and moving one space at a time. I want to visualize this i already got the positions done correctly but the rotations are not quite working yet. Each rotation works correctly from the starting position. But when i rotate or move multiple times it gets buggy.

this is the part of the funtion that dose the calculating it is called once when i press an arrow to look at a previous or next state of the solution:
Code (CSharp):
1. initialRotation = moveableObject.transform.rotation;
2. initialPosition = moveableObject.transform.localPosition;
3.
4.
6. if (prevState != null)
7. {
9.     {
10.         case MoveDirection.Forward:
12.             break;
13.         case MoveDirection.Back:
15.             break;
16.         case MoveDirection.Left:
18.             break;
19.         case MoveDirection.Right:
21.             break;
22.         default:
23.             break;
24.     }
25. }
26.
28. {
29.     case MoveDirection.Forward:
30.         targetRotation = Quaternion.AngleAxis(90f, Vector3.left) * initialRotation;
31.         break;
32.     case MoveDirection.Back:
33.         targetRotation = Quaternion.AngleAxis(90f, Vector3.right) * initialRotation;
34.         break;
35.     case MoveDirection.Left:
36.         targetRotation = Quaternion.AngleAxis(90f, Vector3.back) * initialRotation;
37.         break;
38.     case MoveDirection.Right:
39.         targetRotation = Quaternion.AngleAxis(90f, Vector3.forward) * initialRotation;
40.         break;
41.     default:
42.         break;
43. }
44.
45. elapsedTime = 0f;

the update looks like this:

Code (CSharp):
1. private void Update()
2. {
3.     elapsedTime += Time.deltaTime * animSpeed;
4.
5.
6.     if (elapsedTime < animDuration)
7.     {
8.         float t = elapsedTime / animDuration;
9.         Quaternion newRotation = Quaternion.Slerp(initialRotation, targetRotation, t);
10.         Vector3 newPosition = Vector3.Lerp(initialPosition, targetPosition, t);
11.         moveableObject.transform.rotation = newRotation;
12.         moveableObject.transform.localPosition = newPosition;
13.     }
14.     else
15.     {
16.         moveableObject.transform.rotation = targetRotation;
17.         moveableObject.transform.localPosition = targetPosition;
18.     }
19. }