在固定位置生成 2D 游戏

Spawn in a fix position 2D Game

我正在尝试制作一款多人游戏,但我遇到了生成预制件的问题。我希望这个预制件在 2 个固定位置生成,但我不明白为什么我的脚本不起作用,因为当我开始游戏时,对象在一个位置生成。我创建了一个空游戏对象(我将其命名为 Spawner 并添加了脚本)并添加了 2 个游戏对象( Position1 、 Position2 )作为 Childs。预制件在生成器的位置生成,而不是位置 1 和 2。 这是我使用的脚本。我还必须添加 PhotonView 和 Photon Transform 吗?还有 PunRPC 的东西?

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

public class SpawnPosition : MonoBehaviour
{
    public GameObject[] powersPrefab;
    public Transform[] points;
    public float beat= (60/130)*2;
    private float timer;




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

    // Update is called once per frame
    void Update()
    {
        if (timer > beat)
        {
            GameObject powers = Instantiate(powersPrefab[Random.Range(0, 2)]);
            powers.transform.localPosition = Vector2.zero;
            timer -= beat;

        }
        timer += Time.deltaTime;
    }
}

你总是设置

powers.transform.localPosition = Vector2.zero

对象在没有父对象的根级别上实例化,这等于设置其绝对位置....您始终将其设置为 Unity 原点。


您可能想在 points 中的一个元素的位置生成它,例如:

var powers = Instantiate(
    powersPrefab[Random.Range(0, powersPrefab.Length)], 
    points[Random.Range(0, points.Length)].position, 
    Quaternion.identity
);

请参阅 Instantiate 了解可用的重载。


然而,正如您所说,这是针对多人游戏的,因此您根本不应该使用 Instantiate ,因为这只会在该客户端上生成该对象,而不会在其他客户端上生成.您可能应该确保此生成器仅在您的一个客户端上 运行 并改用 PhotonNetwork.Instantiate

例如

public class SpawnPosition : MonoBehaviour
{
    public GameObject[] powersPrefab;
    public Transform[] points;
    public float beat= (60/130)*2;
    private float timer;

    // Update is called once per frame
    void Update()
    {
        // only run this if you are the master client
        if(!PhotonNetwork.isMasterClient) return;

        if (timer > beat)
        {
            // spawn the prefab object over network
            // Note: This requires you to also reference the prefabs in Photon as spawnable object
            Instantiate(
                powersPrefab[Random.Range(0, 2)].name, 
                points[Random.Range(0, points.Length)].position, 
                Quaternion.identity, 
                0
            );
            timer -= beat;
        }
        timer += Time.deltaTime;
    }
}

这应该有效

void Update() {
        if (timer > beat) {
            GameObject powers = Instantiate(powersPrefab[Random.Range(0, 2)]);
            powers.transform.localPosition = points[Random.Range(0, points.Length)].position;
            timer -= beat;

        }
        timer += Time.deltaTime;
    }
}

你没有分配正确的位置,因为他们没有父母 power.transform.position = Vector2.zero 意味着 power 的全局位置总是 0,0,0。所以你必须像我上面写的那样分配它,它也是随机的。