VRChat U#でPlayerを追いかける処理

VRChatのUdon SharpでPlayerを追いかける処理を書いた時のメモです。
キャラクタの同期はVRC Object Syncで行いました

Inspectorの設定

U#スクリプトは下記です。

using UdonSharp;
using UnityEngine;
using VRC.SDKBase;
using VRC.Udon;

public class Slime_01 : UdonSharpBehaviour
{
    // -- Inspectorから設定する--
    [SerializeField] float movespeed = 0.01f;
    // 同じPlayerに集中しないようInspectorからplayeridを設定
    [SerializeField] int targetplayerid = 0;

    private void Start()
    {
        if (Networking.LocalPlayer.playerId == targetplayerid)
        {
            Networking.SetOwner(Networking.LocalPlayer, this.gameObject);
        }
    }
    private void FixedUpdate()
    {
        // このモンスターのオーナーだけが処理をする
        if (Networking.IsOwner(Networking.LocalPlayer, this.gameObject))
        {
            Vector3 targetHeadPosition = Networking.LocalPlayer.GetBonePosition(HumanBodyBones.Head);
            // 見る
            transform.LookAt(targetHeadPosition);
            // 移動する
            Vector3 newv = transform.position;
            // x方向
            if (transform.position.x > targetHeadPosition.x + 1)
            {
                newv.x = transform.position.x - movespeed;
            }
            else if (transform.position.x < targetHeadPosition.x - 1)
            {
                newv.x = transform.position.x + movespeed;
            }
            // z方向
            if (transform.position.z > targetHeadPosition.z + 1)
            {
                newv.z = transform.position.z - movespeed;
            }
            else if (transform.position.z < targetHeadPosition.z - 1)
            {
                newv.z = transform.position.z + movespeed;
            }
            transform.position = newv;
        }
    }
}

この記事が気に入ったらサポートをしてみませんか?