![](/img/trans.png)
[英]Unity C# 2D Platform game - Projectile doesn't shoot into the direction the player is facing
[英]I was creating a ditto zig zag game i.e. available on Google play store by Ketchapp, Can anyone help me with the specific platform generation?
因此,在上面的圖像中,您可以看到我的腳本生成了平台,盡管我想將生成限制為僅主攝像頭的寬度,即生成的平台不應超出攝像頭屏幕寬度 go。 如果您玩過可用的游戲,您就會知道。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PathGenerator : MonoBehaviour
{
private Vector3 spawnPos;
[SerializeField] Vector3 lastPos;
[SerializeField] float offset;
[SerializeField] GameObject trackPrefab;
private GameObject temp;
[SerializeField] int amountToPool;
List<GameObject> platformPool = new List<GameObject>();
// Start is called before the first frame update
void Start()
{
CreatePath(amountToPool);
UsePath();
}
// Update is called once per frame
void Update()
{
}
private void CreatePath(int amt)
{
for (int i = 0; i < amt; i++)
{
temp = Instantiate(trackPrefab);
temp.transform.SetParent(GameObject.Find("Tracks").transform);
platformPool.Add(temp);
}
}
private void UsePath()
{
foreach (GameObject p in platformPool)
{
RandomPicker();
p.transform.position = spawnPos;
lastPos = p.transform.position;
}
}
public void RespawnTrack(GameObject pathGameObject)
{
RandomPicker();
pathGameObject.transform.position = spawnPos;
lastPos = pathGameObject.transform.position;
}
private void RandomPicker()
{
var randomNumber = Random.Range(0, 2);
if (randomNumber < 1)
{
spawnPos = new Vector3(lastPos.x - offset, 0, lastPos.z);
}
else
{
spawnPos = new Vector3(lastPos.x, 0, lastPos.z - offset);
}
lastPos = spawnPos;
}
}
我想准確地移動我的攝像頭,你也看到了平台如何永遠不會離開屏幕。
為了達到預期的效果,您需要在生成路徑時限制 spawn position。
在您的RandomPicker
function 中,您將下一個 position 設置為在最后一個 position 的右側或左側,在這里您可以限制 position
//.....
float minX, maxX;
float modelWidth = 4;
private void Start()
{
//...rest of the code
minX = Camera.main.ScreenToWorldPoint(Vector2.zero).x + modelWidth;
maxX = Camera.main.ScreenToWorldPoint(Vector2.right * Screen.width).x - modelWidth;
}
private void RandomPicker()
{
//...rest of the code
spawnPos.x = Mathf.Clamp(spawnPos.x, minX, maxX);
lastPos = spawnPos;
}
解決方案說明:可以使用Screen
class 及其static 成員抓取屏幕信息,比如width
。 然而,這將返回“屏幕空間”坐標中的信息,因此我們可以使用Camera.ScreenToWorldPoint
來向上轉換該信息。
此外,為了完全達到預期效果,您需要對齊生成的路徑邊界。 在不同的path
object 大小上執行此操作可能很棘手,因此在創建/設計路徑時請注意路徑的定位和旋轉
使用這種規則時的一些注意事項
Screen
=> 實際游戲屏幕,因此它會反映相機配置和正在運行的游戲(例如可調整大小的窗口)Screen coordinates
中的 Position 零指的是左下角,而“最大”position(使用Screen.height
和Screen.width
)將返回右上角注意:此代碼片段僅適用於正交相機,但可以在透視相機上進行管理。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.