Trigger JS callback on keyframe #5887
-
I'm looking to call a javascript function on a specific keyframe. The use-case for me is in a game: In an attack animation, I want to inflict damage on the target when the animation "hits" its target (which happens at a specific point in the animation, i.e. a keyframe). The function called will affect a completely different component, causing another animation (health loss) to trigger. Is it possible to do this using keyframe animations? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 4 replies
-
Hey! Referring to this section in docs, you can use keyframe animations only for layout entering/exiting animations. So, there is no way to manually control when the keyframe animation is executed. If I understand your desired behavior properly, you could achieve a similar result by storing your players hp in the shared values and play the animation every time the hp shared value decreases. These values should be somehow accessible from in player components (e.g. via shared state, such as context). // Shared state accessible from both players (e.g. PlayersContext)
const player1Hp = useSharedValue(100)
const player2Hp = useSharedValue(100)
// Player component
const { player1Hp: hp } = useContext(PlayersContext) // get your player hp in the player component
const hitAnimationProgress = useSharedValue(0)
useAnimatedReaction(
() => hp.value,
(currentHp, previousHp) => {
if (currentHp < previousHp) {
hitAnimationProgress.value = 0
hitAnimationProgress.value = withTiming(1)
}
}
) Now, you can use const hitAnimationStyle = useAnimatedStyle(
() => ({ opacity: interpolate(hitAnimationProgress.value, [0, 1], [1, 0.5]) })
) This is just a simplified example. |
Beta Was this translation helpful? Give feedback.
Hey!
Referring to this section in docs, you can use keyframe animations only for layout entering/exiting animations. So, there is no way to manually control when the keyframe animation is executed.
If I understand your desired behavior properly, you could achieve a similar result by storing your players hp in the shared values and play the animation every time the hp shared value decreases. These values should be somehow accessible from in player components (e.g. via shared state, such as context).