2013-10-12 66 views
0

我目前正在编写经典的街机游戏C#WPF中的小行星来获得一些练习。 我遇到了一个我似乎无法解决的问题。问题将多个多边形对象添加到画布

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

我有一个generateAsteroids方法,它每20毫秒就会调用一次方法来更新玩家位置等等。 generateAsteroids方法执行各种计算(函数中的注释)以确定要添加到asteroidCollection列表中的多少个小行星。这一切工作正常。

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

我得到以下错误:“ArugementException是未处理由用户代码:指定的可视已经是另一个Visual的孩子或CompositionTarget的根”

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

我已经尝试给每一个添加到画布上的动态名称的多边形。

任何人都知道这个问题请帮帮我吗?

我添加了所有我认为相关的代码,请让我知道,如果你需要看到更多。

感谢

C#:

public void drawAsteroid(Asteroid theAsteroid) 
{ 
    // entityShape is a Polygon object 
    theAsteroid.entityShape.Name = "asteroid" + this.asteroidsAdded.ToString(); 
    theAsteroid.entityShape.Stroke = Brushes.White; 
    theAsteroid.entityShape.StrokeThickness = 2; 
    theAsteroid.entityShape.Points = theAsteroid.getEntityDimensions(); 
    gameCanvas.Children.Add(theAsteroid.entityShape); 
} 

// Called every 20 milliseconds by method that updates the game canvas. Possibly quite inefficient 
public void generateAsteroids() 
{ 
    // Number of asteroids to add to the collection = the length of the game so far/3, then subtract the amount of asteroids that have already been added 
    int asteroidNum = Convert.ToInt32(Math.Ceiling((DateTime.Now - gameStartTime).TotalSeconds/3)); 
    asteroidNum -= asteroidsAdded; 

    for (int i = 0; i <= asteroidNum; i ++) 
    { 
     asteroidCollection.Add(new Asteroid()); 
     this.asteroidsAdded += 1; 
    } 

    foreach (Asteroid asteroid in asteroidCollection) 
    { 
     drawAsteroid(asteroid); 
    } 
} 

XAML:

<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> 

回答

0

drawAsteroid方法您要添加的所有多边形从asteroidCollection到画布上的每个呼叫,不管它们是否已经被添加。但是不能将相同的对象两次添加到WPF面板的Children集合中。这就是为什么你会得到例外(它与Name无关)。

更改您这样的代码:

if (!gameCanvas.Children.Contains(theAsteroid.entityShape)) 
{ 
    gameCanvas.Children.Add(theAsteroid.entityShape); 
} 

当然的代码仍然缺乏逻辑,从不再包含在asteroidCollection画布删除多边形。你还必须补充一点。


而且你也不需要设置多边形的Name对象可言,除非你想用自己的名字后访问它们。