December 04, 2020, 11:34:47 AM

### Author Topic: [bb] Smart Turn by semar [ 1+ years ago ]  (Read 378 times)

#### BlitzBot

• Jr. Member
• Posts: 1
##### [bb] Smart Turn by semar [ 1+ years ago ]
« on: June 29, 2017, 12:28:40 AM »
Title : Smart Turn
Author : semar
Posted : 1+ years ago

Description : Suppose you have a source pivot and want to rotate it toward a target pivot and you need to choose the shortest angle; this function returns the direction where the source pivot should turn, in order to choose the shortest angle path

Code :
Code: BlitzBasic
1. ;=================================================
2. Function where_to_turn(source_pivot,target_pivot)
3. ;=================================================
4. ;parameters:
5. ;   source_pivot:  is the source pivot that we want to turn toward a target pivot
6. ;   target_pivot:  is a target pivot where we want the source pivot to rotate to
7.
8. ;Returned values:
9. ;   0  : no turn needed
10. ;   1  : turn left
11. ;   -1 : turn right
12.
13. temp = Createpivot() ;first, create a temp entity on the source pivot
14.
15. ;position the temp pivot at the source pivot position
16. PositionEntity temp,EntityX(source_pivot),EntityY(source_pivot),EntityZ(source_pivot)
17.
18. PointEntity temp,target_pivot ;turns the temp pivot to the target pivot
19. ;now temp pivot has the yaw that the source should have
20.
21. ;memo start angle and end angle, I just consider the integer parts of it, using Floor
22. s = Floor(EntityYaw(source_pivot)) ;this is the start yaw angle, that is, the current yaw orientation of the source
23. t = Floor(EntityYaw(temp))         ;this is the end angle, that is, the angle we should reach
24.
25. FreeEntity (temp)  ;release the temp entity, we do not need it from now
26.
27. If s = t Then ;if the two angles are the same we do not need any rotation !
28.         Return 0
29. EndIf
30.
31. ;the angle goes from 0,180 and 0,-180; now I normalize to 0-360
32. If s < 0 Then s = 360 + s
33. If t < 0 Then t = 360 + t
34.
35. ;now we found the right direction where to turn, in order to choose the shortest path:
36.
37. ;check if the difference is greather than 180
38. If Abs(s-t) > 180 Then
39.
40.         ;check if the start angle is greater than the target angle
41.         If s > t Then
42.                 Return 1 ;turn left
43.         Else
44.                 Return -1 ;turn right
45.         EndIf
46. Else
47.         ;check if the start angle is greater than the target angle
48.         If s > t Then
49.                 Return -1 ;turn right
50.         Else
51.                 Return  1 ;turn left
52.         EndIf
53.
54. EndIf
55.
56. End Function