I’m working on a project challenge. I’ve previously made a flag quiz game where there are three buttons made by a ForEach loop with images as flags. The challenge is to animate the flags so that the tapped flag is rotated 360 degrees and the others aren’t. I’ve completed the challenge (and the following challenges) successfully. Here is a chunk my code:
@State private var rotDegrees = 0.0
@State private var notPickedOpacity = 1.0
@State private var scaling = 1.0
...
ForEach(0..<3){ number in
Button{
flagTapped(number)
whichFlagTapped = number
withAnimation {
rotDegrees += 360
notPickedOpacity -= 0.75
scaling -= 0.2
}
} label: {
FlagImage(imageName: countries[number])
}.rotation3DEffect(
whichFlagTapped == number ? .degrees(rotDegrees) : .degrees(0),
axis: (x:0.0, y:1.0, z:0.0)
)
.opacity(whichFlagTapped == number ? 1.0 : notPickedOpacity)
.scaleEffect(whichFlagTapped == number ? 1.0 : scaling)
}
...
func askQuestion(){
if numQuestionsAsked < 8 {
countries.shuffle()
correctAnswer = Int.random(in: 0...2)
numQuestionsAsked += 1
notPickedOpacity = 1.0
scaling = 1.0
} else {
isGameOver = true
}
}
While this works fine with explicit animation, I’m trying to figure out why it works better than with implicit animation. Here is what I’ve got in the loop for implicit animation (focusing only on the rotation this time).
ForEach(0..<3){ number in
Button{
flagTapped(number)
whichFlagTapped = number
rotDegrees += 360
} label: {
FlagImage(imageName: countries[number])
}.rotation3DEffect(
whichFlagTapped == number ? .degrees(rotDegrees) : .degrees(0),
axis: (x:0.0, y:1.0, z:0.0)
)
.animation(.default, value: rotDegrees)
}
In this case, the tapped answer does rotate by 360 degrees when tapped (sometimes more?), but the previous answer also rotates back to 0.
So I’m wondering, why is it that in the explicit animation case this rotation back to 0 does not happen? Or maybe the flag’s rotation is actually set to 0 (and not animated since it is only animating the change of rotDegrees?) – but in this case shouldn’t picking the flag in that position later on cause it to rotate by some multiple of 360 back up to rotDegrees? Since then the flag’s rotation will need to be animated from 0 up to the new rotDegrees? I think I’m missing something important about explicit animation here.