Apply a physicsobjectbehavior via code

Aug 20, 2009 at 12:43 PM

I have been trying to apply a physics object behavior via code but it doesn't seem to be taking effect. I have a controller object attached to my root but when I click a button to attach it an objectbehavior to an Ellipse it does not take effect. However, if i drag the behavior onto my Ellipse in the gui and start the game, it applies fine. Can anyone help?

Cheers!

 

 Ellipse newCoin = new Ellipse();
            newCoin.Height = 10;
            newCoin.Width = 10;
            SolidColorBrush colorBrush = new SolidColorBrush();
            colorBrush.Color = Colors.Yellow;
            newCoin.Fill = colorBrush;
            BehaviorCollection behaviorCollection = Interaction.GetBehaviors(newCoin);
            behaviorCollection.Add(new PhysicsObjectBehavior());
            LayoutRoot.Children.Add(newCoin);
            int x = 133;
            int y = 20;
            Canvas.SetLeft(newCoin, x);
            Canvas.SetTop(newCoin, y);
            TranslateTransform newPos = new TranslateTransform();
            newPos.X = x;
            newPos.Y = y;
            newCoin.RenderTransform = newPos; Ellipse newCoin = new Ellipse();

            BehaviorCollection behaviorCollection = Interaction.GetBehaviors(newCoin);

            behaviorCollection.Add(new PhysicsObjectBehavior());

            LayoutRoot.Children.Add(newCoin);

 

Coordinator
Aug 20, 2009 at 1:19 PM

What you're doing makes perfect sense, it just doesn't work with the way the PhysicsController is designed - because physics elements are processed at Load time.

You can still add elements dynamically, you just need to do it differently - if you look at "DemoBehaviors2" (the RagDoll demo) then there is an example in the button click. The key is the AddPhysicsBodyForCanvasWithBehaviors method (long winded eh?) and below is an example.

        PhysicsControllerMain _physicsController;

        public MainPage()
        {
            InitializeComponent();
            this.Loaded += new RoutedEventHandler(MainPage_Loaded);
        }

        void MainPage_Loaded(object sender, RoutedEventArgs e)
        {
            // NOTE that cnvGame is where you placed the PhysicsControllerBehavior
            _physicsController = cnvGame.GetValue(PhysicsControllerMain.PhysicsControllerProperty) as PhysicsControllerMain;
        }

        private void btnAddDoll_Click(object sender, RoutedEventArgs e)
        {
            ucRagDoll _ucRagDollNew = new ucRagDoll();
            cnvGame.Children.Add(_ucRagDollNew);

             _ucRagDollNew.SetValue(Canvas.LeftProperty, Convert.ToDouble(_rand.Next(50, 950)));
            _ucRagDollNew.SetValue(Canvas.TopProperty, 0D);

            _physicsController.AddPhysicsBodyForCanvasWithBehaviors(_ucRagDollNew.LayoutRoot);
        }

Coordinator
Aug 26, 2009 at 1:06 PM

I also did a blog post around this -

http://www.andybeaulieu.com/Home/tabid/67/EntryID/168/Default.aspx