我想创建一款多人射击游戏。我写了这段代码:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Photon.Pun;
public class MultiWeapon : MonoBehaviour
{
PhotonView view;
public GameObject bullet;
public Camera mainCamera;
public Transform spawnBullet;
public float shootForce;
public float spread;
public AudioSource _audio;
private void Awake() {
view = GetComponent<PhotonView>();
_audio = GetComponent<AudioSource>();
}
void Update()
{
if (Input.GetMouseButtonDown(0))
Shoot();
}
private void Shoot()
{
_audio.Stop();
Ray ray = mainCamera.ViewportPointToRay(new Vector3(0.5f, 0.5f, 0));
RaycastHit hit;
Vector3 targetPoint;
if (Physics.Raycast(ray, out hit))
targetPoint = hit.point;
else
targetPoint = ray.GetPoint(75);
Vector3 dirWithoutSpread = targetPoint - spawnBullet.position;
float x = Random.Range(-spread, spread);
float y = Random.Range(-spread, spread);
Vector3 dirWithSpread = dirWithoutSpread + new Vector3(x, y, 0);
GameObject currentBullet = Instantiate(bullet, spawnBullet.position, Quaternion.identity);
currentBullet.transform.forward = dirWithSpread.normalized;
currentBullet.GetComponent<Rigidbody>().AddForce(dirWithSpread.normalized * shootForce, ForceMode.Impulse);
_audio.time = 0.15f;
_audio.Play();
}
}
当我从两个设备启动游戏时,会发生这种情况:从第一个设备射击时,两个玩家都会射击,而在第二个设备上则看不到射击。怎么解决?
要解决此问题,您应该修改 Shoot 方法,在处理射击动作之前检查附加到 GameObject 的 PhotonView 是否属于本地玩家。以下是修改代码的方法:
void Update()
{
// Only allow the local player to shoot.
if (view.IsMine && Input.GetMouseButtonDown(0))
{
Shoot();
}
}
通过在条件中添加 view.IsMine,您可以确保仅当 PhotonView 由本地玩家控制时才执行射击动作。
此外,您需要确保当调用 Instantiate 创建子弹时,应该通过网络完成,以便所有玩家都可以看到它。您应该使用 Photon 的实例化方法来执行此操作,如下所示:
GameObject currentBullet = PhotonNetwork.Instantiate(bullet.name, spawnBullet.position, Quaternion.identity);
这将确保在所有客户的游戏中通过网络创建子弹。请注意,要使其工作,子弹预制件必须位于“资源”文件夹中,并在 Photon 的设置中正确设置为网络感知。
最后,确保您的子弹预制件附加有 PhotonView 组件以及通过网络同步其位置和销毁的脚本。如果没有正确的同步,其他玩家可能无法正确看到子弹或其效果。
希望这个答案对你有帮助👍