我正在创建一个游戏,需要一些帮助处理一堆物体,比如大约10000,在我的游戏中我生成随机数量的岩石,在1mil到1mil地图周围的随机位置,我正在添加对象一个列表,并更新和绘制它们,但它运行得如此之慢。我认为这方面的一些帮助确实可以帮助很多想要处理许多对象的学习者。 这是我的代码:
public void WorldGeneration()
{
//Random Compatibility
Random rdm = new Random();
//Tile Variables
int tileType;
int tileCount = 0;
Rock nearestRock;
//Initialize Coordinates
Vector2 tileSize = new Vector2(48f, 48f);
Vector2 currentGenVector = new Vector2(48f, 48f);
int worldTiles = 1000000;
//Do tile generation
for(int tile = 1; tile <= worldTiles; tile += 1)
{
//Generate Classes
tileType = rdm.Next(0, 42);
if (tileType == 1)
{
if (rocks.Count != 0)
{
//Check Rock Distance
nearestRock = rocks.FirstOrDefault(x => Vector2.Distance(x.Location, currentGenVector) < 128);
if (nearestRock == null)
{
Rock rock = new Rock(rockSprite, currentGenVector);
rocks.Add(rock);
}
}
if (rocks.Count == 0)
{
Rock rock = new Rock(rockSprite, currentGenVector);
rocks.Add(rock);
}
}
//Move Generation Tile
if (tileCount == worldTiles / 1000)
{
currentGenVector.X = tileSize.X;
currentGenVector.Y += tileSize.Y;
tileCount = 0;
}
else
{
currentGenVector.X += tileSize.X;
}
//Keep Count of Tiles per layer.
tileCount += 1;
}
这是我的摇滚代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Graphics;
namespace Game2
{
class Rock
{
//Draw Support
Texture2D sprite;
Rectangle drawRectangle;
//Support
Vector2 location;
bool updating = false;
//Active
bool active = true;
public Rock(Texture2D sprite, Vector2 location)
{
//Initialize Location/Drawing
this.sprite = sprite;
this.location = location;
drawRectangle.Width = sprite.Width;
drawRectangle.Height = sprite.Height;
drawRectangle.X = (int)location.X - sprite.Width / 2;
drawRectangle.Y = (int)location.Y - sprite.Height / 2;
}
public void Update(GameTime gameTime, MouseState mouse)
{
//Mining
if (drawRectangle.Contains(mouse.X, mouse.Y))
{
if (mouse.LeftButton == ButtonState.Pressed)
{
location.X = -800;
location.Y = -800;
}
}
drawRectangle.X = (int)location.X;
drawRectangle.Y = (int)location.Y;
}
public void Draw(SpriteBatch spriteBatch)
{
//Draws The Sprite
spriteBatch.Draw(sprite, drawRectangle, Color.White);
}
//Get Location
public Vector2 Location
{
get { return location; }
}
public bool Updating
{
get { return updating; }
}
public void setUpdating(bool updating)
{
this.updating = updating;
}
public Rectangle DrawRectangle
{
get { return drawRectangle; }
}
}
}
我只想问一些关于如何处理所有这些对象的技巧, 请帮助表示赞赏
答案 0 :(得分:0)
我处理许多对象的方法是创建一个函数来计算两个向量之间的距离,然后用它来检查当前对象是否足够接近绘制。
//Distance checking code
public float GetDistance(Vector2 v1, Vector2 v2){
float d = Math.Sqrt(Math.Abs((v1.X * v1.X) - (v2.X * v2.X))
+ Math.Abs((v1.Y * v1.Y) - (v2.Y * v2.Y)));
return d;
}
//example of using the Distance Check
if(GetDistance(player.position, rock.position) < 1280){
rock.Update();
}
这只是我的头脑,所以代码可能无法正常工作,但我认为这足以让你开始。祝你好运!