facebook twitter hatena line email

Unity/photon/pun1/位置同期/シンプル

提供: 初心者エンジニアの簡易メモ
2017年10月18日 (水) 09:12時点におけるAdmin (トーク | 投稿記録)による版 (ページの作成:「==位置同期のサンプル== #ヒエラルキーにCubeを作成 #CubeにAddComponentをしてPhotonViewを追加 #Cubeに以下CubeScript.csも割り当てる。 #Cub...」)

(差分) ←前の版 | 最新版 (差分) | 次の版→ (差分)
移動: 案内検索

位置同期のサンプル

  1. ヒエラルキーにCubeを作成
  2. CubeにAddComponentをしてPhotonViewを追加
  3. Cubeに以下CubeScript.csも割り当てる。
  4. CubeのInspectorのPhotonViewのObserverdOptionにCubeを指定する
  5. ヒエラルキーのCubeをプロジェクトのResourcesにプレハブとして追記する(ドラッグ)
  6. 部屋入室時に以下コードを実行
void OnJoinedRoom() {
    GameObject cube = PhotonNetwork.Instantiate ("Cube", new Vector3 (0.0f, 0.0f, 0.0f), 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;

移動をスムーズにするには

  1. 移動させるオブジェクトのInspectorを開き
  2. PhotonTransformViewをAddComponentから追加する
  3. 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