Skip to main content
Version: 0.4.1

Bone follower

Keeps an object on a bone of a player's avatar: a halo over a head, a balloon tied to a hand or a trail at the feet. It follows the local player, or the nearest other player when followNearestOther is on. Pick the bone with bone, nudge it with offset and turn on matchRotation to turn with the bone too. Each device moves its own copy with GetBonePosition, so the script needs no synced variables.

If the avatar has no such bone (not every avatar has a jaw or toes), GetBonePosition returns Vector3.zero and the object stays where it is. Arms on desktop and phones are animated on each device, so a hand can be a little apart between two players' screens. See Players.

BoneFollower.cs
using StageTime.SDK;
using UnityEngine;

/// <summary>
/// Keeps this object on a bone of a player's avatar: a halo over a head, a balloon tied to a hand, a trail at the feet.
/// By default it follows the local player; turn on <c>followNearestOther</c> to put it on the nearest other player
/// instead. Each device moves its own copy, so nothing is synced. Shows <c>GetBonePosition</c> and <c>GetBoneRotation</c>.
/// </summary>
public class BoneFollower : StageTimeBehaviour
{
[Tooltip("The bone to follow.")]
public STBone bone = STBone.Head;
[Tooltip("Where to sit relative to the bone, in metres (y is up).")]
public Vector3 offset = new Vector3(0f, 0.3f, 0f);
[Tooltip("Follow the nearest other player instead of the local player.")]
public bool followNearestOther;
[Tooltip("Turn with the bone as well (off: only the position follows).")]
public bool matchRotation;

private StageTimePlayer[] players = new StageTimePlayer[0];

private void LateUpdate()
{
StageTimePlayer target = followNearestOther ? NearestOther() : Networking.LocalPlayer;
if (target == null) return;

Vector3 position = target.GetBonePosition(bone);
if (position == Vector3.zero) return; // this avatar has no such bone
transform.position = position + offset;
if (matchRotation) transform.rotation = target.GetBoneRotation(bone);
}

private StageTimePlayer NearestOther()
{
StageTimePlayer me = Networking.LocalPlayer;
if (me == null) return null;
int count = StageTimePlayer.GetPlayerCount();
if (players.Length != count) players = new StageTimePlayer[count];
StageTimePlayer.GetPlayers(players);

Vector3 here = me.GetPosition();
StageTimePlayer nearest = null;
float best = float.MaxValue;
for (int i = 0; i < players.Length; i++)
{
StageTimePlayer p = players[i];
if (p == null || p.isLocal) continue;
float d = (p.GetPosition() - here).sqrMagnitude;
if (d < best) { best = d; nearest = p; }
}
return nearest;
}
}