学习视频:
- Unity多人联机游戏API Mirror学习(四)-- 双打乒乓球 1
- Unity多人联机游戏API Mirror学习(五)-- 双打乒乓球 2
Ball
创建一个Sphere,改名为Ball1,为Ball1 添加 RigidBody , Network Transform , Network Identity
为 Ball1 添加脚本 Ball1.cs :
using UnityEngine;
using Mirror;
public class Ball1 : NetworkBehaviour
{
public float speed = 10f;
private Rigidbody rig;
private Vector3 vel = new Vector3(0, 0, 0);
public override void OnStartServer()
{
base.OnStartServer();
rig = GetComponent<Rigidbody>();
}
[ServerCallback]
private void OnCollisionEnter(Collision collision)
{
float y = collision.relativeVelocity.y > 0 ? 1 : -1;
vel.y = y * speed;
rig.velocity = vel;
}
}
Player
修改Player Prefab:
Network Manager1
继承于 NetworkManager
using UnityEngine;
using Mirror;
[AddComponentMenu("")]
public class NetworkManager1 : NetworkManager
{
GameObject player;
private Vector3 lhs = new Vector3(-2, -2, 0);
private Vector3 rhs = new Vector3(2, -4, 0);
public override void OnServerAddPlayer(NetworkConnection conn)
{
if (numPlayers == 0)
{
player = Instantiate(playerPrefab, lhs, transform.rotation);
}
else if (numPlayers == 1)
{
player = Instantiate(playerPrefab, rhs, transform.rotation);
}
NetworkServer.AddPlayerForConnection(conn, player);
}
}
(要记得给新的 Network Manager 添加 Player Prefab)
|