2013-07-24 23 views
1

希望你能幫上忙。對一些人來說,陷入一個簡單的問題,我是一個小菜鳥。試圖做的是讓Silverlight/C#中的圖像對象從畫布的頂部隨機放置,此時它從右向左移動。Silverlight C#圖像對象

這是來自對象類。

namespace LOLWordGame 
{ 
    public class LetterA : ContentControl, IGameEntity 
    { 
     private int speed = 0; 

     public LetterA() 
     { 
      Image LetterImage = new Image(); 
      LetterImage.Height = 45; 
      LetterImage.Width = 45; 
      LetterImage.Source = new BitmapImage(new Uri("images/a.png", UriKind.RelativeOrAbsolute)); 
      this.Content = LetterImage; 

      Random random = new Random(); 
      Canvas.SetLeft(this, -20); 
      Canvas.SetTop(this, random.Next(250, 850)); //randomly 
      speed = random.Next(1, 5); 
     } 

     public void Update(Canvas c) 
     { 
      Move(Direction.Down); 
      if (Canvas.GetLeft(this) < 100) 
      { 
       c.Children.Remove(this); 
      } 
     } 

     public void Move(Direction direction) 
     { 
      Canvas.SetLeft(this, Canvas.GetLeft(this) - speed); 
     } 
    } 
} 

在此先感謝。

回答

0

對於一個解決方案:也許你應該使用Canvase.SetTop Method而不是SetLeft方法?希望這可以幫助。

次要的..我敢肯定下面的代碼不是解決你的問題,但我重構了一下。嘗試使用collection initializers。你有一個方法Move,你只能調用一次,該方法只有一行代碼:沒有理由在我看來這樣做的方法。此外,該方法需要一個參數,但不在方法內部使用它。

public class LetterA : ContentControl, IGameEntity 
{ 
    private int speed = 0; 

    public LetterA() 
    { 
     var letterImage = new Image() 
     { 
      Height = 45, 
      Width = 45, 
      Source = new BitmapImage(new Uri("images/a.png", UriKind.RelativeOrAbsolute)) 
     }; 
     Content = letterImage; 

     var random = new Random(); 
     Canvas.SetLeft(this, -20); 
     Canvas.SetTop(this, random.Next(250, 850)); 
     speed = random.Next(1, 5); 
    } 

    public void Update(Canvas c) 
    { 
     Canvas.SetLeft(this, Canvas.GetLeft(this) - speed); 
     if (Canvas.GetLeft(this) < 100) 
      c.Children.Remove(this); 
    } 
} 
+0

感謝您的幫助Abbas –