You are currently viewing 【Unity教學】2022製作多人連線遊戲的最佳選擇!Photon Fusion 03 角色移動

【Unity教學】2022製作多人連線遊戲的最佳選擇!Photon Fusion 03 角色移動

  • Post category:教學
  • Reading time:4 mins read
  • Post author:

大家好,我是Wilson,這次的教學會帶大家學會如何在Fusion中讓角色移動以及輸入控制!

領取Photon Fusion 快速上手懶人攻略

這邊幫大家準備了【Photon Fusion 快速上手懶人攻略】!

裡面介紹了Fusion的基本功能,以及Fusion同步網路狀態的3大方法,有興趣的朋友可以免費領取喔!

重點回顧

  • 要送Input之前,要先用struct包裝資料並實作INetworkInput
  • 包裝好的Input資料要在INetworkRunnerCallbacks中的OnInput()提供
  • 要擁有網路的屬性,要繼承NetworkBehaviour
  • 要更新網路上的狀態,要使用FixedUpdateNetwork()
  • 可以透過GetInput()方法來獲取輸入,並套用在角色身上

PlayerRef說明圖示

Code

NetworkInputData.cs

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Fusion;

public struct NetworkInputData : INetworkInput
{
    public Vector3 movementInput;
}

BasicSpawner.cs 的 OnInput()

public void OnInput(NetworkRunner runner, NetworkInput input)
{
    var data = new NetworkInputData();

    if (Input.GetKey(KeyCode.W))
        data.movementInput += Vector3.forward;

    if (Input.GetKey(KeyCode.S))
        data.movementInput += Vector3.back;

    if (Input.GetKey(KeyCode.A))
        data.movementInput += Vector3.left;

    if (Input.GetKey(KeyCode.D))
        data.movementInput += Vector3.right;

    input.Set(data);
}

PlayerController.cs

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Fusion;

public class PlayerController : NetworkBehaviour
{
    [SerializeField]
    private NetworkCharacterControllerPrototype networkCharacterController = null;

    [SerializeField]
    private float moveSpeed = 15f;

    public override void FixedUpdateNetwork()
    {
        if (GetInput(out NetworkInputData data))
        {
            Vector3 moveVector = data.movementInput.normalized;
            networkCharacterController.Move(moveSpeed * moveVector * Runner.DeltaTime);
        }
    }
}

專案GitHub

這次進度的專案可以在這裡看到!

This Post Has 4 Comments

  1. car buyer

    You need to be a part of a contest for one of the finest sites on the web.

    I’m going to highly recommend this blog!

  2. 401

    Hey there I aam so grateful I found yoyr web site, I reaally found
    you by accident,while I was lookming oon Yahoo for something else, Regaedless
    I amm hefe nnow and wokuld jist like tto sayy thank yoou
    foor a remarkmable post annd a alll round enjoyable blo (I also love the theme/design),I
    don’t havve tume to read it all att thhe mlment buut I have book-marked it
    and also added yopur RSS feeds, so when I have time I will be back to
    read more, Plase do keep up the fantasstic work.

  3. 044

    Hey there! I juust wanted to ask iff you ever have any trouble with hackers?
    My lwst blog (wordpress) was hacked aand I ended up losing a
    few mmonths of hard ork duue to no back up. Do you have any metyhods too prevent hackers?

  4. Doreen

    Thiss information iis priceless. Hoow caan I find out more?

Leave a Reply