Unity는 LAN 게임을 어떻게 만듭니까?

1. 게임 소개

LAN 연결을 구현하는 온라인 게임으로, 테이블 게임과 유사하며 테이블 위에 여러 개의 사각형이 있고 파괴된 사각형의 수가 일정 수에 도달하면 승리합니다.

2. 게임 구현

1. LAN 관리를 담당하는 NetworkManager라는 빈 개체를 만듭니다.

 2. NetworkManeger에 두 개의 구성 요소를 추가합니다(아래 참조).

 

 3. 실행을 클릭하면 인터페이스에 여러 개의 버튼이 있는 것을 볼 수 있는데 첫 번째 버튼은 클라이언트 생성이고 두 번째 버튼은 서버에 연결하는 것입니다. 

 4. 하나의 평면과 네 개의 큐브로 데스크탑을 만들고 특정 색상을 지정합니다. 효과는 다음과 같습니다.

5. 여러 개의 큐브를 만들고 태그를 볼로 변경하고 적절한 위치에 놓습니다.

6. 작은 공을 만들고 이름을 플레이어로 지정하고 태그를 플레이어로 변경하고 구성 요소 NetworkIdentity를 추가합니다.

7. 스크립트 이동을 생성하고 공을 움직이도록 공을 할당합니다.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
public class move : MonoBehaviour
{
    public float speed = 6.0f;
    public float gravity = -9.8f;
    private CharacterController _charController;
    // Start is called before the first frame update
    void Start()
    {
        _charController = GetComponent<CharacterController>();//使用附加到相同对象上的其他组件
    }
 
    // Update is called once per frame
    void Update()
    {
        float x = Input.GetAxis("Horizontal") * speed;
        float z = Input.GetAxis("Vertical") * speed;
        Vector3 movement = new Vector3(x, 0, z);
        movement = Vector3.ClampMagnitude(movement, speed);//使对角移动的速度和沿轴移动的速度一样
        movement.y = gravity;
        movement *= Time.deltaTime;
        movement = transform.TransformDirection(movement);//本地坐标变为全局坐标
        _charController.Move(movement);//character通过movement向量移动
    }
}

8. 새 폴더 prefabs를 만들고 플레이어를 prefab으로 드래그한 다음 장면에서 플레이어를 삭제합니다. 다음과 같이 플레이어를 NetworkManager로 드래그합니다.

9. 공이 블록에 닿은 후 블록이 사라지도록 플레이어 코드 이동 수정(공은 블록의 레이블, 블록의 레이블이 공으로 변경되지 않으면 파괴되지 않음), rigid body 컴포넌트 추가 플레이어에게(프리팹에서 공을 선택하고 맨 오른쪽에서 Open Prefab을 선택하고 구성 요소를 추가합니다.)

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;

public class move : MonoBehaviour
{
    public float speed = 100;

    // Start is called before the first frame update
    void Start()
    {
      
    
    }

    // Update is called once per frame
    void FixedUpdate()
    {
        float moveh = Input.GetAxis("Horizontal");
        float movev = Input.GetAxis("Vertical");
        Vector3 movement = new Vector3(moveh, 0.0f, movev);
        GetComponent<Rigidbody>().AddForce(movement * speed * Time.deltaTime);//给小球施加力,使小球运动
    }
    void OnCollisionEnter(Collision other)
    {
        if (other.gameObject.tag == "ball")
        {
            Destroy(other.gameObject);//小球碰到标签为pickup的物体则摧毁物体
         
        }
   
    }
 

}

 10. 실행을 클릭한 후 클라이언트를 생성하는 인터페이스의 첫 번째 버튼을 클릭하면 공이 생성되는 것을 볼 수 있습니다.

11. 장면을 내보내고(파일—>빌딩 설정——>빌드, 적절한 폴더 선택) 내보낸 후 실행하고 장면에서 두 번째 버튼을 클릭하여 클라이언트에 연결합니다(동일한 컴퓨터에서 실행 중인 경우). , 직접 연결할 수 있음) 다음 인터페이스가 나타나고 장면에 두 명의 플레이어가 있음을 알 수 있습니다(그러나 버그가 있고 화면이 동기화되지 않고 두 끝이 함께 움직이는 등) 추후 수정).

 

 12. 화면 동기화 문제 해결, 클라이언트와 서버 구분

1) 플레이어에 두 개의 구성 요소를 추가하고 관련 매개 변수를 다음과 같이 설정합니다.

2) 플레이어의 식별 구성 요소 설정

 

 3) 이동 코드 재작성

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
using UnityEngine.Networking;

public class move : NetworkBehaviour
{
    public float speed = 100;

    // Start is called before the first frame update
    void Start()
    {
      
    
    }

    // Update is called once per frame
    void FixedUpdate()
    {
        if (isLocalPlayer) {//判断当前客户端是不是自己
            playermove();
        }
    }

    public override void OnStartLocalPlayer()//客户端已连接就会调用
    {
        transform.GetComponent<Renderer>().material.color = Color.green;
     //   base.OnStartLocalPlayer();
    }

    void OnCollisionEnter(Collision other)
    {
        if (other.gameObject.tag == "ball")
        {
            Destroy(other.gameObject);//小球碰到标签为pickup的物体则摧毁物体
         
        }
   
    }
    private void playermove() {
        float moveh = Input.GetAxis("Horizontal");
        float movev = Input.GetAxis("Vertical");
        Vector3 movement = new Vector3(moveh, 0.0f, movev);
        GetComponent<Rigidbody>().AddForce(movement * speed * Time.deltaTime);//给小球施加力,使小球运动
    }
 

}

이런 식으로 LAN 연결이 실현됩니다! ! !

Supongo que te gusta

Origin blog.csdn.net/lxy20011125/article/details/130380961
Recomendado
Clasificación