如何在每个级别的位置只绘制一次,并检查位置是否唯一
本文关键字:位置 一次 唯一 是否 检查 绘制 | 更新日期: 2023-09-27 18:21:45
就像在标题中一样,我想从List<Vector2> positions = new List<Vector2>{/*here i got 9 vectors*/}
获得职位,但我只想获得其中的一些。
例如,在第1级中,我只想从该列表中随机检查第2级中的1个位置,以此类推…
//making that in switch statement where i check which level user actually is
Random rnd = new Random();
List<Vector2> list = new List<Vector2>();
byte i = 0;
byte level; // number from 0 to 9 changing where level complited;
while(i < level){
list.Add(positions[rnd.Next(0,10)]);
i++;
}
我的问题是如何随机这个位置,每个级别只有一个,现在我可以随机,但它一直在变化。我用画法画的。
这个位置我应该在哪里抽签?在更新方法或其他地方?
编辑:随机检查意味着我只想从列表中获得1个Vector2,但使用随机类来随机化每个级别,现在清楚了吗?我不知道怎样才能更简单地解释这一点:(
第1版:
以及如何防止从列表中获得相同的位置我的意思是如何检查我的列表中的Vector2是否被绘制(是唯一的)。
感谢提前:)
在加载级别的方法中执行。在while循环中添加一个i++
。
编辑
好吧,我明白你现在的意思了:一个用于一级,两个用于二级等等
您的代码是可以的,并且将执行您想要的操作,但是将其放入draw方法(或更新)是错误的,因为这些方法经常执行。
您应该使用一个特殊的方法来加载一个新级别。当你检测到一个关卡已经完成时,你可以调用这个方法,它会清理上一个关卡的资源(比如重置玩家位置、生命、弹药等)。然后你将构建新的关卡-放置敌人等等,这包括你指定的代码。
我希望我已经讲清楚了。
这是一个原型:
int _lives;
int _ammo;
List<Vector2> _positions;
Vector2 _playerPosition;
int _currentLevel;
void LoadLevel(int level)
{
_currentLevel = level;
_playerPosition = Vector2.Zero;
_lives = 3;
_ammo = 100;
List<Vector2> list = new List<Vector2>();
Random rnd = new Random();
int i = 0;
while(i < level)
{
list.Add(_positions[rnd.Next(0,10)]);
i++;
}
...
}
然后在您的更新中:
protected void Update(GameTime gameTime)
{
if(goToNextLevel) //here you put your condition that advances to next level;
{
LoadLevel(_currentLevel+1);
}
}
第2版
要从列表中获取以前没有的另一个项目,您可以创建一个临时列表,然后从中删除项目而不仅仅是选择它们。
我还没有测试过这个代码,但它会像这样:
List<Vector2> list = new List<Vector2>();
List<Vector2> tempList = new List<Vector2>(_positions);
Random rnd = new Random();
int i = 0;
while(i < level)
{
int index = rnd.Next(tempList.Count); //random goes up to number of items
list.Add(tempList[index]); //add the randomed item
tempList.RemoveAt(index); //remove the randomed item from the temporary list.
i++;
}
...