LoginLogin

sprite rotation question

Root / Programming Questions / [.]

spaceturtlesCreated:
How do you rotate a sprite to a direction without it taking "the long way around"? Here's my code so far in the main loop:
WHILE 1
 STICK OUT SX, SY
 IF (ABS(SX)>0.4)||(ABS(SY)>0.4) THEN
  TROT=-DEG(ATAN(SY,SX)) 'Sprite's at a weird angle
  IF ROT!=TROT THEN IF (ROT-TROT)<(TROT-ROT) THEN INC ROT,4 ELSE DEC ROT,4
  SPROT 0,ROT
  ENDIF
 VSYNC
 WEND
I tried to fix it with more IF statements using (ROT-TROT)>(TROT-ROT) but that didn't work.

Yeah it's complicated and annoying. Basically you need a function to find the distance (positive or negative) between 2 angles:
DEF ANGDIST(A1#,A2#)
 A1#=A1#-A2#+PI()
 RETURN A1#-2*PI()*FLOOR(A1#/(2*PI()))-PI()
END
'Or, a simpler but possibly slightly less precise version:
DEF ANGDIST(A1,A2)
 RETURN ATAN(SIN(A1-A2),COS(A1-A2))
END
And then you check whether ANGDIST(ROT,TROT) is greater than or less than 0.

Yeah it's complicated and annoying. Basically you need a function to find the distance (positive or negative) between 2 angles:
DEF ANGDIST(A1#,A2#)
 A1#=A1#-A2#+PI()
 RETURN A1#-2*PI()*FLOOR(A1#/(2*PI()))-PI()
END
'Or, a simpler but possibly slightly less precise version:
DEF ANGDIST(A1,A2)
 RETURN ATAN(SIN(A1-A2),COS(A1-A2))
END
And then you check whether ANGDIST(ROT,TROT) is greater than or less than 0.
Didn't realize their was an answer until yesterday. I tried it out but the sprite just shakes rapidly and doesn't turn much. Any ideas of what went wrong?

Yeah it's complicated and annoying. Basically you need a function to find the distance (positive or negative) between 2 angles:
DEF ANGDIST(A1#,A2#)
 A1#=A1#-A2#+PI()
 RETURN A1#-2*PI()*FLOOR(A1#/(2*PI()))-PI()
END
'Or, a simpler but possibly slightly less precise version:
DEF ANGDIST(A1,A2)
 RETURN ATAN(SIN(A1-A2),COS(A1-A2))
END
And then you check whether ANGDIST(ROT,TROT) is greater than or less than 0.
Didn't realize their was an answer until yesterday. I tried it out but the sprite just shakes rapidly and doesn't turn much. Any ideas of what went wrong?
Make sure you convert to degrees

If current angle is 0 deg and target angle is 2 deg, current angle goes back and forth between 0 and 4. I guess that is the reason why your sprite shakes rapidly. I recommend you to apply SPANIM to avoid sprite shaking as follows.
ACLS
SPSET 0,3481
SPOFS 0,200,120,0
SPSCALE 0,2,2

WHILE 1
STICK OUT SX,SY

IF(ABS(SX)>0.4)||(ABS(SY)>0.4)THEN
 SPROT 0 OUT ROT:ROT=RAD(ROT)
 TROT=ATAN(-SY,SX)+PI()/2
 DR=TROT-ROT
 DR=DEG(ATAN(SIN(DR),COS(DR)))
 DT=ABS(DR)DIV 4:DT=DT+(DT<=0)

 SPANIM 0,"R+",-DT,DR,1
ENDIF
VSYNC
WEND

Thanks problem solved
Spoiler"i=you're mom gay" no u