silverlight 碰撞检测

原内容
http://www.andybeaulieu.com/Default.aspx?tabid=67&EntryID=95
private bool CheckCollision(FrameworkElement control1, FrameworkElement controlElem1, FrameworkElement control2, FrameworkElement controlElem2)
        
{
            
// first see if sprite rectangles collide
            Rect rect1 = UserControlBounds(control1);
            Rect rect2 
= UserControlBounds(control2);


            rect1.Intersect(rect2);
            
if (rect1 == Rect.Empty)
            
{
                
// no collision - GET OUT!
                return false;
            }

            
else
            
{
                
bool bCollision = false;
                Point ptCheck 
= new Point();

                
// now we do a more accurate pixel hit test
                for (int x = Convert.ToInt32(rect1.X); x < Convert.ToInt32(rect1.X + rect1.Width); x++)
                
{
                    
for (int y = Convert.ToInt32(rect1.Y); y < Convert.ToInt32(rect1.Y + rect1.Height); y++)
                    
{
                        ptCheck.X 
= x;
                        ptCheck.Y 
= y;

                        List
<UIElement> hits = System.Windows.Media.VisualTreeHelper.FindElementsInHostCoordinates(ptCheck, control1) as List<UIElement>;
                        
if (hits.Contains(controlElem1))
                        
{
                            
// we have a hit on the first control elem, now see if the second elem has a similar hit
                            List<UIElement> hits2 = System.Windows.Media.VisualTreeHelper.FindElementsInHostCoordinates(ptCheck, control2) as List<UIElement>;
                            
if (hits2.Contains(controlElem2))
                            
{
                                bCollision 
= true;
                                
break;
                            }

                        }

                    }

                    
if (bCollision) break;
                }

                
return bCollision;
            }



        }





        
public Rect UserControlBounds(FrameworkElement control)
        
{
            Point ptTopLeft 
= new Point(Convert.ToDouble(control.GetValue(Canvas.LeftProperty)), Convert.ToDouble(control.GetValue(Canvas.TopProperty)));
            Point ptBottomRight 
= new Point(Convert.ToDouble(control.GetValue(Canvas.LeftProperty)) + control.Width, Convert.ToDouble(control.GetValue(Canvas.TopProperty)) + control.Height);

            
return new Rect(ptTopLeft, ptBottomRight);
        }
判断control1中的controlElem1是否以碰到control2的controlElem2 demo:
获取 Microsoft Silverlight
posted @ 2009-08-27 20:25  _Chill  阅读(1155)  评论(1编辑  收藏  举报