Python Usage Examples#
Controlling the timeline#
This example demonstrates how to use various API functions to control the timeline’s state:
import omni.timeline
# Obtain the main timeline object
timeline = omni.timeline.get_timeline_interface()
# Start playing the timeline
timeline.play()
# Check if the timeline is playing
# Output will be False as state changes are applied in the next frame
print(f'Is the timeline playing? {timeline.is_playing()}')
# Set the current time to t = 3 seconds
timeline.set_current_time(3)
# Perform additional operations...
# Pause the timeline
timeline.pause()
# Advance the timeline by one frame
# Frame duration can be adjusted using timeline.set_time_codes_per_second
timeline.forward_one_frame()
Registering callbacks for timeline state changes#
The following code example shows how to register a callback to respond to various timeline state changes:
import omni.timeline
from carb.eventdispatcher import get_eventdispatcher
# Obtain the main timeline object
timeline = omni.timeline.get_timeline_interface()
# Define a callback function to handle timeline events
def on_timeline_events(event):
if event.event_name == omni.timeline.GLOBAL_EVENT_CURRENT_TIME_TICKED:
# Difference between the last current time and the new one
# Clamped to zero if it would be negative
dt = event['dt']
# Retrieve the new current time
current_time = event['currentTime']
print(f'Current time changed, dt = {dt}s, end of frame = {current_time}s')
if event.event_name == omni.timeline.GLOBAL_EVENT_PLAY:
print(f'Timeline is now playing')
if event.event_name == omni.timeline.GLOBAL_EVENT_STOP:
print(f'Timeline is now stopped')
if event.event_name == omni.timeline.GLOBAL_EVENT_PAUSE:
print(f'Timeline is now paused')
if event.event_name == omni.timeline.GLOBAL_EVENT_START_TIME_CHANGED:
start_time = event['startTime']
print(f'Timeline has a new start time: {start_time}s')
# For more events, please consult the TimelineEventType documentation
# Register for the event types we care about
# NOTE: Typically it is better to have separate handler functions for each event type
timeline_subs = [
get_eventdispatcher().observe_event(
filter=timeline.get_event_key(),
event_name=event_name,
on_event=on_timeline_events
)
for event_name in (
omni.timeline.GLOBAL_EVENT_CURRENT_TIME_TICKED,
omni.timeline.GLOBAL_EVENT_PLAY,
omni.timeline.GLOBAL_EVENT_STOP,
omni.timeline.GLOBAL_EVENT_PAUSE,
omni.timeline.GLOBAL_EVENT_START_TIME_CHANGED
)
]
# Demonstrate the callback functionality by triggering various timeline events
timeline.set_start_time(1)
timeline.play()
timeline.set_current_time(3)
timeline.pause()
timeline.stop()