在固定位置生成 2D 游戏 [英] Spawn in a fix position 2D Game
问题描述
我正在尝试制作多人游戏,但在生成预制件时遇到问题.我希望这个预制件在 2 个固定位置生成,但我不明白为什么我的脚本不起作用,因为当我开始游戏时,对象在一个位置生成.我创建了一个空的游戏对象(我将其命名为 Spawner 并添加了脚本)并添加了 2 个游戏对象( Position1 、 Position2 )作为 Childs.预制件生成在 Spawner 的位置,而不是位置 1 和 2 .这是我使用的脚本.我还必须添加 PhotonView 和 Photon Transform 吗?和 PunRPC 的东西?
I am trying to do a multiplayer game and I have a problem with spawning prefabs. I want this prefabs to be spawn in 2 fix position but I don't understand why my script doesn't work because when I start the game the objects are spawn in one position. I created an empty game object( I named it Spawner and added the script) and added 2 game objects ( Position1 , Position2 ) as Childs. The prefab is spawn in the position of the Spawner and not position 1 and 2 . Here is the script I used. Also do I have to add to it PhotonView and Photon Transform ? and something with 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;
}
}
推荐答案
这应该可行
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.所以你必须像我上面写的那样分配它,它也是随机的.
You are not assigning right position, and since they are parentless power.transform.position = Vector2.zero
means that power's global position would always 0,0,0. So you must assign it as I wrote above, and it's also randomized.
这篇关于在固定位置生成 2D 游戏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!