C# 向画布添加多个多边形对象时出现问题

C# 向画布添加多个多边形对象时出现问题,c#,wpf,canvas,addchild,C#,Wpf,Canvas,Addchild,我目前正在用C#WPF编程经典的街机游戏《小行星》,以获得一些练习。 我遇到了一个我似乎无法解决的问题 我在生成小行星并添加到包含所有游戏对象的画布元素时遇到问题 我有一个GenerateEasteroids方法,每20毫秒调用一次,通过更新玩家船位置的方法等等。GenerateEasteroids方法执行各种计算(函数中的注释),以确定要添加到小行星集合列表中的小行星数量。这一切都很好 当我尝试将小行星多边形对象添加到游戏画布时,问题就出现了 我收到以下错误:“用户代码未处理Arugement

我目前正在用C#WPF编程经典的街机游戏《小行星》,以获得一些练习。 我遇到了一个我似乎无法解决的问题

我在生成小行星并添加到包含所有游戏对象的画布元素时遇到问题

我有一个GenerateEasteroids方法,每20毫秒调用一次,通过更新玩家船位置的方法等等。GenerateEasteroids方法执行各种计算(函数中的注释),以确定要添加到小行星集合列表中的小行星数量。这一切都很好

当我尝试将小行星多边形对象添加到游戏画布时,问题就出现了

我收到以下错误:“用户代码未处理ArugementException:指定的Visual已是另一个Visual的子级或CompositionTarget的根”

现在我明白了这意味着什么(我想),所有的小行星对象都被称为“小行星”,这显然是不理想的,我研究发现,你不能动态地为运行中的对象创建变量名

我尝试过在每次将多边形添加到画布时为多边形指定一个动态名称

知道这个问题的人能帮我吗

我已经添加了所有我认为相关的代码,如果您需要查看更多,请告诉我

谢谢

C#:

小行星(小行星)
{
//entityShape是一个多边形对象
theAsteroid.entityShape.Name=“asteroid”+this.asteroidsAdded.ToString();
theAsteroid.entityShape.Stroke=画笔.白色;
theAsteroid.entityShape.StrokeThickness=2;
theAsteroid.entityShape.Points=theAsteroid.getEntityDimensions();
gameCanvas.Children.Add(theAsteroid.entityShape);
}
//更新游戏画布的方法每20毫秒调用一次。可能效率很低
公共void GeneratorEasteroids()
{
//要添加到集合中的小行星数量=游戏到目前为止的长度/3,然后减去已添加的小行星数量
int asternonum=Convert.ToInt32(数学上限((DateTime.Now-gameStartTime.TotalSeconds/3));
Asternonum-=小行星装载;

对于(int i=0;i在
drawAsteroid
方法的每次调用中,您都将
asteroidCollection
中的所有多边形添加到画布,无论它们是否已添加。但是您不能将同一对象两次添加到WPF面板的
子对象
集合中。这就是为什么会出现异常(它与
名称
无关)

按如下方式更改代码:

if (!gameCanvas.Children.Contains(theAsteroid.entityShape))
{
    gameCanvas.Children.Add(theAsteroid.entityShape);
}
当然,代码仍然缺乏从画布中删除不再包含在
集合中的多边形的逻辑。您还必须添加这些多边形


而且您根本不需要设置多边形对象的
名称
,除非您以后想通过名称访问它们

<Window x:Name="GameWindow" x:Class="AsteroidsAttempt2.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Width="1000" Height="1000" HorizontalAlignment="Left" VerticalAlignment="Top" Loaded="GameWindow_Loaded">

<Canvas x:Name="GameCanvas" Focusable="True" IsEnabled="True" HorizontalAlignment="Left" Height="1000" VerticalAlignment="Top" Width="1000" KeyDown="GameCanvas_KeyDown"  KeyUp="GameCanvas_KeyUp">
    <Canvas.Background>
        <ImageBrush ImageSource="D:\CPIT\BCPR283\Asteroids\Asteroids\AsteroidsAttempt2\Resources\SpaceBackground.jpg" Stretch="Fill"/>
    </Canvas.Background>
</Canvas>
if (!gameCanvas.Children.Contains(theAsteroid.entityShape))
{
    gameCanvas.Children.Add(theAsteroid.entityShape);
}