gpt4 book ai didi

c# - unity2d : randomly change position of gameobject after it has been looped

转载 作者:太空宇宙 更新时间:2023-11-03 22:54:48 25 4
gpt4 key购买 nike

所以,我正在制作这个小游戏,其中角色通过自动滚动相机不断向上移动。角色从一个平台跳到另一个平台,一旦平台或背景图 block 不再可见,我就会将它循环回去。我为我的平台分配了一个范围,随机发生器从中选择一个值,这样玩家每次开始游戏时都会获得一组单独的平台。问题是循环:因为我在 start() 函数中进行了随机化,所以平台的随机位置只分配一次,然后一次又一次地循环。所以游戏在 20 秒后循环几次后变得有点无聊 :D

这是我的代码:

private float randomFloat = 0;
private int subOrAdd = 0;

// Use this for initialization
void Start () {

subOrAdd = Random.Range(1, 10);
randomFloat = Random.Range(0f, 1.4f);

// randomly add or subtract height of object
if (subOrAdd < 6)
{
this.transform.position = new Vector2(transform.position.x, transform.position.y - randomFloat);
}
else if (subOrAdd >= 6)
{
this.transform.position = new Vector2(transform.position.x, transform.position.y + randomFloat);
}

}

基本上,我有一个硬编码范围,然后随机决定添加或减去超出范围的数字。那么我将如何做到这一点,让循环的对象总是要求一个新的位置?因为如您所知,start 只被调用一次,即使在循环之后,位置仍然保持不变。我希望我在这里说清楚了:)

任何帮助都会很棒!

这是循环平台的代码:

public class PlattformLooper : MonoBehaviour {

public float spacingBetweenLoops = 0f;

private void OnTriggerEnter2D(Collider2D collider)
{
if (collider.gameObject.tag == "Plattform")
{
Debug.Log("TRIGGERED Plattform!");

float heightOfBGObj = ((BoxCollider2D)collider).size.y;

Vector3 pos = collider.transform.position;

pos.y += heightOfBGObj * (5*5)+spacingBetweenLoops;

collider.transform.position = pos;
}
}

最佳答案

只需将您的随机化逻辑提取到一个单独的方法中即可。

void Start () {
RandomizeHeight()
}

public void RandomizeHeight() {
subOrAdd = Random.Range(1, 10);
randomFloat = Random.Range(0f, 1.4f);

// randomly add or subtract height of object
if (subOrAdd < 6)
{
this.transform.position = new Vector2(transform.position.x, transform.position.y - randomFloat);
}
else if (subOrAdd >= 6)
{
this.transform.position = new Vector2(transform.position.x, transform.position.y + randomFloat);
}
}

然后你可以随时调用它:

public class PlattformLooper : MonoBehaviour {

public float spacingBetweenLoops = 0f;

private void OnTriggerEnter2D(Collider2D collider)
{
if (collider.gameObject.tag == "Plattform")
{
Debug.Log("TRIGGERED Plattform!");

float heightOfBGObj = ((BoxCollider2D)collider).size.y;

Vector3 pos = collider.transform.position;

pos.y += heightOfBGObj * (5*5)+spacingBetweenLoops;

collider.transform.position = pos;
collider.GetComponent<YourComponent>().RandomizeHeight();
}
}

关于c# - unity2d : randomly change position of gameobject after it has been looped,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45896801/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com