Unity/photon/pun1/位置同期/シンプル
ナビゲーションに移動
検索に移動
位置同期のサンプル
- ヒエラルキーにCubeを作成
- CubeにAddComponentをしてPhotonViewを追加
- Cubeに以下CubeScript.csも割り当てる。
- CubeのInspectorのPhotonViewのObserverdOptionにCubeを指定する
- ヒエラルキーのCubeをプロジェクトのResourcesにプレハブとして追記する(ドラッグ)
- 部屋入室時に以下コードを実行
void OnJoinedRoom() {
GameObject cube = PhotonNetwork.Instantiate("Cube", Vector3.zero, Quaternion.Euler(Vector3.zero),0);
}
CubeScript.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CubeScript : MonoBehaviour {
void Awake () {
if (GetComponent<PhotonView>().isMine) {
GetComponent<Renderer>().material.color = Color.red;
}
}
void OnMouseDrag()
{
Debug.Log ("ownerId=" + GetComponent<PhotonView>().ownerId);
Debug.Log ("isMine=" + GetComponent<PhotonView>().isMine);
if (GetComponent<PhotonView>().isMine) {
GetComponent<Renderer>().material.color = Color.red;
Vector3 objectPointInScreen = Camera.main.WorldToScreenPoint (this.transform.position);
Vector3 mousePointInScreen = new Vector3 (Input.mousePosition.x,
Input.mousePosition.y,
objectPointInScreen.z);
Vector3 mousePointInWorld = Camera.main.ScreenToWorldPoint (mousePointInScreen);
mousePointInWorld.z = this.transform.position.z;
this.transform.position = mousePointInWorld;
}
}
}
注意
以下コードがfalseになっていると離脱後もインスタンスが残るので注意。
PhotonNetwork.autoCleanUpPlayerObjects = true;
移動をスムーズにするには
- 移動させるオブジェクトのInspectorを開き
- PhotonTransformViewをAddComponentから追加する
- SyncronizePositionにチェックを入れる
参考
- Unity Photon(PUN+) の使い方 オブジェクト位置同期編(4/5)
http://sleepnel.hatenablog.com/entry/2016/06/09/120200
- 【Unity】僕もPhotonを使いたい #07 位置の同期
http://www.urablog.xyz/entry/2016/09/19/232345
- 公式
https://doc.photonengine.com/ja-jp/pun/current/manuals-and-demos/instantiation