0% found this document useful (0 votes)
3 views

07-Animation

The document provides an overview of animation concepts, including frames, frame rates, tweening, easing, and keyframes, essential for simulating movement in graphics. It discusses the implementation of animation in programming, particularly through timers and callbacks, and highlights the importance of managing UI thread interactions. Additionally, it covers various animation techniques and tools, including built-in timers, Java Util Timer, and third-party libraries.

Uploaded by

yejoyce8
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

07-Animation

The document provides an overview of animation concepts, including frames, frame rates, tweening, easing, and keyframes, essential for simulating movement in graphics. It discusses the implementation of animation in programming, particularly through timers and callbacks, and highlights the importance of managing UI thread interactions. Additionally, it covers various animation techniques and tools, including built-in timers, Java Util Timer, and third-party libraries.

Uploaded by

yejoyce8
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 32

Animation

▪ Frames and Frame Rate


▪ Simulation
▪ Timer
▪ Tweening
▪ Easing
▪ Keyframes
▪ System Timers (and UI Threading)

Animation 1
Animation

Animation is the simulation of movement using a series of images


(or drawings, models, etc.)

IMAGE SOURCE: https://www.angryanimator.com/word/2010/11/26/tutorial-2-walk-cycle/ Animation 2


Animation Terminology

Frame: each image (or state) of an animation sequence


Frame rate: number of frames to display per second
Tweening: interpolation of key frames into frames
Easing: a function that controls how tweening is calculated
Key Frame: defines the beginning and ending of a tween

In user interface programming, we typically animate numerical


parameters that change how graphics are drawn over time
- parameters are often related to transformations
(e.g. translate X and Y position to animate drawing position)
- parameters can be anything numeric: fill, stroke weight, etc.
- animating non-numeric values (e.g. a String or Image) is possible,
but custom tweening methods are needed

Animation 3
Frame Rate

▪ Measured in frames-per-second (fps)


- can be expressed as Hertz (Hz): International System of Units (SI)
measure defined as one cycle per second (e.g. 60 FPS = 60 Hz)
▪ Common device and media frame rates:
- hand drawn animation: as low as 12 FPS, usually 24 fps
- GIFs: usually 15 to 24 fps
- Film: standard 24 fps, high def 60 fps
- Legacy Broadcast Television: NTSC: 30 fps*, PAL 25 fps*
- Computer displays: 60 fps or more
- Computer games: 60 fps or more
- Virtual Reality displays: 90 fps, 120 fps, or more

* each frame is sent progressively in two parts: odd “scanlines”, even “scanlines”,
so communication speed is technically 60 Hz for NTSC and 50 Hz for PAL

Animation 4
Critical Flicker Frequency* (CFF)

▪ when perception of intermittent light source changes from


flickering to continuous light
- dependent on brightness of stimulus, wavelength, ...
- varies by individual

CFF is typically
around 60 – 90 Hz

*also called “flicker fusion threshold”, “temporal contrast sensitivity”

IMAGE SOURCE: https://entokey.com/temporal-properties-of-vision/ Animation 5


Zoetrope, mechanical example of CFF
https://youtu.be/8UC8j4pg1iA
Animation 6
Animation in SimpleKit

▪ SimpleKit lets you define a single callback for updating animations


- callback is called with time (in milliseconds) as argument

▪ in simplekit

type AnimationCallback = (time: number) => void;

function setSKAnimationCallback(animate: AnimationCallback) ...

▪ in your program

setSKAnimationCallback((time) => { /* animate in here */ });

Animation 7
Animation by Simulation

▪ Animation can be created through real time simulation


- using functions, conditionals, etc.

▪ Typically, no start and end, it just loops or continues


- conceptually simpler, just need a function and/or some rules

Animation 8
simulation

▪ dot moves in direction with speed, bounces when boundary hit


- set animation callback bounce()

// if it hits the edge of the box, change direction


if (dot.x < dot.r || dot.x > box.width - dot.r) {
dx *= -1.0;
}
...

// update the dot position


dot.x += dx;
dot.y += dy;

▪ also demo of moving dot in circle


- Call circle() in animation callback

Animation 9
Timers

▪ A timer can be considered a simple kind of animation


- State 1 ... wait ... State 2

▪ A timer needs
- a duration
- a start time
- an update function to check if timer is finished
- a method to check if timer is running
- (usually) a callback function to call when timer is finished

Animation 10
timer simpleTimerDemo()

▪ Useful to trigger UI changes after some time


▪ Basic timer object
- construct it with duration
- start it with current time (from animation callback or skTime)
- update with current time in animation callback
- use isRunning property to trigger event

export class BasicTimer {


constructor(public duration: number) {}
...

Animation 11
timer callbackTimerDemo()

▪ CallbackTimer to call function when time finishes


- construct it with duration and callback function
- start it with current time
- update with current time in animation callback
- calls callback when finished with time

export class CallbackTimer extends BasicTimer {


constructor(
public duration: number,
public callback: (t: number) => void) {}
...

▪ How to make dot pulse on and off every second?

Animation 12
Tweening

Interpolation between keyframes to create individual frames


- we’ll consider “keyframes” as numeric values

Tweening Parameters
startValue is the starting value for the tween (keyframe 1)
endValue is the end value for the tween (keyframe 2)
duration is the duration for the tween
startTime is when the tween begins
Tweening Calculation
1) Calculate proportion of time completed so far:
t = (time – startTime) / duration
2) Interpolate start and end value to get current tweened value:
value = startValue + (endValue – startValue) * t

Animation 13
lerp function

linear interpolation
▪ smoothly interpolate changes from one value to another
▪ lerp is a fundamental part of animation tweening

// linear interpolation from start to end


// using normalized time t (in [0, 1])
const lerp = (start: number, end: number, t: number) =>
start + (end - start) * t;

Animation 14
tweening

▪ Basic animation object


- construct it with animation parameters and update value callback
(called every frame with new interpolated value)
- start it with current time, update with time in animation callback

export class Animator {


constructor(
public startValue: number,
public endValue: number,
public duration: number,
public updateValue: (p: number) => void
) {}
...
▪ Why does Animator force t to be 1 when
time is elapsed? → remove that code and
animate for 200ms to see what happens
Animation 15
Easing Functions

Controls how tweening is calculated


Lerp generates a linear change in value over time t
value = lerp(startValue, endValue, t)
An easing function changes how value is interpolated over time t
value = lerp(startValue, endValue, easing(t))

[VIDEO SOURCE] https://www.alanzucconi.com/2021/01/24/piecewise-interpolation/easing-curves// Animation 16


Easing Functions

▪ Type
type EasingFunction = (t: number) => number;

▪ Common functions
exponent changes the
const flip = (t) => 1 - t; "amount" of easeOut

const easeOut = (t) => Math.pow(t, 2);

const easeIn = (t) => flip(easeOut(flip(t)));

const easeInOut = (t) => lerp(easeOut(t), easeIn(t), t);

Animation 17
easing

▪ Animation object with optional easing function

export class Animator {


constructor(
public startValue: number,
public endValue: number,
public duration: number,
public updateValue: (p: number) => void,
public easing: EasingFunction = (t) => t
) {}

...

Animation 18
Easing Function Resources

▪ http://robertpenner.com/easing/
▪ https://greensock.com/docs/v3/Eases
▪ https://www.febucci.com/2018/08/easing-functions/

[VIDEO SOURCE] https://www.alanzucconi.com/2021/01/24/piecewise-interpolation/easing-curves// Animation 19


UI Toolkit Animation Architecture

▪ Some toolkits provide an animation manager


- keep a list of active animations
- update each animation every frame
- remove animations when they finish

▪ Programmer sets animation, lets toolkit manage everything

Animation 20
manager

▪ AnimationManager singleton with list of active Animator objects

class AnimationManager {
protected animations: Animater[] = [];

add(animation: Animator) {
this.animations.push(animation);
...
}

update(time: number) {
// update every animation currently running
this.animations.forEach(
(a) => a.update(time));

// remove animations that finished


this.animations =
this.animations.filter(
(a) => a.isRunning);
}
Animation 21
Keyframing

▪ A tween is essentially two keyframes:


- keyframe 1: start time, starting value
- keyframe 2: end time, ending value

▪ We can generalize this to a list of keyframes:


- keyframe 1: time1, value1
- keyframe 2: time2, value2
- keyframe 3: time3, value3
...
- keyframe N: timeN, valueN

▪ A sequence of keyframes enables animations over time:


- find keyframe i and keyframe i + 1 for current time
(time >= keyframe[i].time) && (time <= keyframe[i+1].time)
- tween value as keyframe i and value as keyframe i + 1

Animation 22
Keyframing Example
Example 1
when time is 800,
time targetValue tween keyframe 0 and keyframe 1:
t = (800 – 0) / (1000 – 0)
0: 0 100
value = 100 + t * (300 - 100)
keyframes

1: 1000 300 Example 2


when time is 3000,
tween keyframe 2 and keyframe 3:
2: 2500 400 t = (3000 – 2500) / (5000 – 2500)
value = 400 + t * (50 - 400)
3: 5000 50
Practice:
when time is 5250
4: 6000 50

when time is 7000


5: 6500 100

Animation 23
keyframes

▪ Array of KeyFrame objects

const keyframes: KeyFrame[] = [


{ time: 0, targetValue: 50 },
{ time: 1000, targetValue: 450 },
...

▪ Keyframer object
- find interval in keyframe array using time
- tween to get current value
- call callback

▪ Comments
- how to insert pauses as keyframes?

Animation 24
Animation Using Built-in Timers

A timer triggers an event after some time period


1. Set time period to time interval for desired frame rate
e.g. 30 FPS has an interval of 1/30 seconds (~33 milliseconds)
2. In the timer “finished” event handler, do:
- update parameters you want to animate
- (optional) redraw an updated image for the frame
3. restart the timer for the next interval
- some timers can repeat automatically at a set interval

timer = Timer(() => {


x += 1 // animate parameter
draw() // redraw scene
}

pseudo code
Animation 25
dom-timers demoIntervalTimer()

▪ The DOM / HTML engine has a general-purpose interval timer


- try different frame rates by changing interval, what happens?

const duration = 2000;


let timer = setInterval(() => {
const timePassed = performance.now() - start;
dot.x = lerp(50, 250, timePassed / duration);
gc.clearRect(0, 0, canvas.width, canvas.height);
dot.draw(gc);
// stop after certain time
if (timePassed > duration) {
clearInterval(timer);
}
}, 1000 / 60);

1000 ms / 60 frames = 16.666 ms/frame = 60 FPS

Check assignment specification,


using this timer may not be allowed.
Animation 26
dom-timers demoRequestAnimationFrame()

▪ The DOM / HTML engine provides a special animation callback


- this is what SimpleKit uses to create the run-loop

const duration = 2000;


requestAnimationFrame(function animate(timePassed) {
dot.x = lerp(50, 250, timePassed / duration);
gc.clearRect(0, 0, canvas.width, canvas.height);
dot.draw(gc);
// continue unless done animation
if (timePassed < duration) {
requestAnimationFrame(animate);
}
});

Check assignment specification,


using this timer may not be allowed.
Animation 27
Timers and the UI Thread

▪ Most (all?) UI frameworks are single-threaded (e.g. JavaFX)


- partly because its simpler and multiple threads isn't needed
- a single threaded dispatch queue avoids deadlocks and race
conditions due to unpredictable user-generated events
▪ Most (all?) UI frameworks are typically not thread-safe
- to reduce execution burden, reduce complexity, etc.

▪ Most modifications to the UI must be on the UI execution thread


- otherwise, behaviour may be unexpected
- or in some cases, an exception is thrown

This has implications for animation timers in those frameworks


- HTML DOM interval and animation timers run on the UI thread
- Other platforms may have timers running on a non-UI thread

Animation 28
Animation using Java Util Timer
import java.util.* This code is Kotlin with JavaFX

// create timer
val timer = Timer()

// schedule a task to repeat


timer.scheduleAtFixedRate(
// WARNING! This task is NOT executed on the JavaFX thread!
object : TimerTask() {
override fun run() {
aniScene.x += 1.0 // animate parameter
aniScene.draw() // redraw updated scene
}
},
0, 1000/60
)

This type of timer does not run on the JavaFX UI


thread: it may cause an exception if modifications to the
scene graph are attempted in the event handler.
Animation 29
Animation using Java Util Timer with JavaFX Runnable
import java.util.* This code is Kotlin with JavaFX
import javafx.application.Platform

// create timer
val timer = Timer()

// schedule a task to repeat


timer.scheduleAtFixedRate(

object : TimerTask() {
override fun run() {
// runs the code on the JavaFX thread
Platform.runLater {
aniScene.x += 1.0 // animate parameter
aniScene.draw() // redraw updated scene
}
}
},
0, 1000/60
)

Animation 30
Standard Animation API and Libraries

▪ CSS Transitions and Animation


- https://developer.mozilla.org/en-
US/docs/Web/CSS/CSS_animations/Using_CSS_animations
- can control with TypeScript by creating and manipulating styles

▪ Many 3rd party animation libraries


- GreenSock https://greensock.com/
- can animate any JavaScript object field
- many easing functions
- keyframing system

Check assignment specification, using CSS animations


or external animation libraries may not be allowed.
Animation 31
Exercise
EXERCISE
▪ Draw green 64px square
▪ If mouse click on square:
- turn square to blue for 2s
▪ If mouse click not on square:
- animate square centre to click
position over 1s
▪ Use SimpleKit
- draw callback
- event handler
- animation update
Hint: create a Square shape class
that holds all of its state (position,
fill, timer, animations, ...).

Video demo:
https://vault.cs.uwaterloo.ca/s/trNbEgP24p4mbas

Animation 32

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy