Playing an animation clip using scripts¶
Overview¶
In this tutorial, you will learn how to:
- Find an animation clip in Asset Library.
- Configure it in your Space.
- Play it by using a LUA script.
Getting an appropriate animation clip¶
First of all, you need to find an appropriate animation clip to play in your Space. Go to Asset Library to browse animation clips.
Find and add an animation clip named "Wave Hip Hop Dance_Wave Hip Hop Danceā.
Getting an appropriate model and binding the animation clip to it¶
Find an appropriate model for this animation clip. As for now, these animation clips in Asset Library can only apply to humanoid models. Find the humanoid model named "BackRoomsCharacter01" and put it in your Space.
To bind the animation clip to your model, you need a community component (Component) named "Animation-play ability." It can be found in Asset Library as well.
Attach this Component to your chosen model and bind your animation clip by choosing Animation clip.
Turning this model into an AnimatorController¶
Only an animator controller can play animation clips. You can turn a model from Asset Library into an AnimatorController by making it a non-player character(NPC). Attaching a Monster component makes the model an NPC.
Playing the animation¶
Create a script and attach it to the model you've added to the Space.
-
Create an entity for the object, which is the model you put in the scene. Then check if the entity is an animator controller as only an animator controller can play an animation clip.
local _selfEntity = script:SelfEntity() if not YaAnimatorAPI.IsAnimatorController(_selfEntity) then return end
-
Get an AnimatorControllerEntity using the entity and then you can play the animation clip by its name. In this tutorial, you will play the animation clip called "Wave Hip Hop Dance_Wave Hip Hop Dance".
local _selfEntity = script:SelfEntity() if not YaAnimatorAPI.IsAnimatorController(_selfEntity) then return end local _animatorControllerEntity = YaAnimatorAPI.Instance(_selfEntity) local _handle = _animatorControllerEntity:Play("Wave Hip Hop Dance_Wave Hip Hop Dance")
-
Set the animation to loop using
_handle:SetLooping(true)
. -
Add an event to trigger the animation clip to play.
local _selfEntity = script:SelfEntity() function OnAvatarSpawned(playerId, spawnPointEntity, avatarEntity) if not YaAnimatorAPI.IsAnimatorController(_selfEntity) then return end local _animatorControllerEntity = YaAnimatorAPI.Instance(_selfEntity) local _handle = _animatorControllerEntity:Play("Wave Hip Hop Dance_Wave Hip Hop Dance") _handle:SetLooping(true) end function OnPlayerJoined(playerId) local player = YaGame:GetPlayer(playerId) EventHelper.AddListener(player, "SpawnedEvent", OnAvatarSpawned) end EventHelper.AddListener(YaGame, "PlayerJoinedEvent", OnPlayerJoined)
-
Save the script and playtest it in Play Mode.