好的,所以我的游戏开始几乎可以工作了现在这一切都有效,我正试图让碰撞工作。问题是它不起作用。
如果有人知道它为什么不起作用以及如何开始工作,我已经注释掉了不起作用的碰撞编码,请告诉我如何。
当我取消注释时出错:
The best overloaded method match for 'System.Windows.PresentationFrameworkCollection.Add(System.Windows.UIElement)' has some invalid arguments
我的代码(主页)
命名空间游戏
{
公共(public)部分类 MainPage : UserControl
{
pig 我的 pig ;
列出我的苹果;
private int appleTimer = 0;
//int appleCount = 0;
public MainPage()
{
InitializeComponent();
myPig = new Pig();
myapples = new List<Apple>();
Image myImg = new Image();
myImg.Source = new BitmapImage(new Uri("pig3.png", UriKind.Relative));
myImg.Width = 80;
myImg.Height = 60;
myPig.Content = myImg;
LayoutRoot.Children.Add(myPig);
Canvas.SetLeft(myPig,100);
Canvas.SetTop(myPig, 50);
//LayoutRoot.Children.Add(myapples);
CompositionTarget.Rendering += new EventHandler(CompositionTarget_Rendering);
}
public void AddApple(Apple a)
{
myapples.Add(a);
LayoutRoot.Children.Add(a);
}
public void RemoveApple(Apple a)
{
myapples.Remove(a);
LayoutRoot.Children.Remove(a);
}
public void CompositionTarget_Rendering(object sender, EventArgs e)
{
appleTimer += 1;
if (appleTimer > 60)
{
appleTimer = 0;
AddApple(new Apple());
}
for (int indx = 0; indx < myapples.Count; indx++)
{
myapples[indx].Update(LayoutRoot);
}
// if (DetectCollision(myapples, myPig))
{
// LayoutRoot.Children.Remove(myapples);
}
}
private void UserControl_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Up)
this.myPig.Move(Direction.Up);
if (e.Key == Key.Down)
this.myPig.Move(Direction.Down);
if (e.Key == Key.Left)
this.myPig.Move(Direction.Left);
if (e.Key == Key.Right)
this.myPig.Move(Direction.Right);
}
public bool DetectCollision(ContentControl ctrl1, ContentControl ctrl2)
{
Rect ctrl1Rect = new Rect(
new Point(Convert.ToDouble(ctrl1.GetValue(Canvas.LeftProperty)),
Convert.ToDouble(ctrl1.GetValue(Canvas.TopProperty))),
new Point((Convert.ToDouble(ctrl1.GetValue(Canvas.LeftProperty)) + ctrl1.ActualWidth),
(Convert.ToDouble(ctrl1.GetValue(Canvas.TopProperty)) + ctrl1.ActualHeight))
);
Rect ctrl2Rect = new Rect(
new Point(Convert.ToDouble(ctrl2.GetValue(Canvas.LeftProperty)),
Convert.ToDouble(ctrl2.GetValue(Canvas.TopProperty))),
new Point((Convert.ToDouble(ctrl2.GetValue(Canvas.LeftProperty)) + ctrl2.ActualWidth),
(Convert.ToDouble(ctrl2.GetValue(Canvas.TopProperty)) + ctrl2.ActualHeight))
);
ctrl1Rect.Intersect(ctrl2Rect);
return !(ctrl1Rect == Rect.Empty);
}
}
}
最佳答案
你有一个元素列表,而不是一个元素。遍历列表并添加每个元素:
foreach (Apple a in myapples) {
LayoutRoot.Children.Add(a);
}
关于c# - C#中对象的碰撞检测,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22078914/