1

希望你能帮忙。对某些人来说,我只是一个简单的问题,我是菜鸟。尝试做的是让 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);
        }
    }
}

提前致谢。

4

1 回答 1

0

解决方案:也许您应该使用Canvase.SetTop 方法而不是 SetLeft 方法?希望这可以帮助。

次要的..我确定以下代码不能解决您的问题,但我对其进行了一些重构。尝试使用集合初始化器。您有一个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);
    }
}
于 2013-07-24T11:54:55.903 回答