Silverlight 解谜游戏 之四 粒子特效

       前几篇一直在Blend中工作没体现出开发者的作用,本篇将为订书器(Stapler)添加自定义粒子效果,当订书器被点击时产生更好的视觉效果。其中将使用到nerdplusartSilverlight Particle Generator 粒子特效工具。

在结束本章内容后,点击Stapler 和Candies 将达到以下效果:

Get Microsoft Silverlight

 

 

1. 在Projects面板中新增Interactivity 文件夹,再为Interactivity 新增ParticlesBehavior 子文件夹:

folder

2. 右键ParticlesBehavior文件夹->Add New Item->Behavior,添加ParticlesBehavior

newitem

itemlist

3. 下载Silverlight Particle Generator 源代码,将代码中的ParticleControl.xamlParticleControl.xaml.cs 文件加入(Add Existing Item)到ParticlesBehavior 文件夹:

file

4. 右键项目点击“Edit in Visual Studio”,对PaticlesBehavior.cs进行编辑来跟踪鼠标移动位置。将ParticlesBehavior 类声明改为Behavior<Canvas>,通过修改后AssociatedObject 类型将成为Canvas。在OnAttached 和OnDetaching 方法中分别添加和删除MouseMove 事件,当鼠标移动时便可记录下当前鼠标位置:

public class ParticlesBehavior : Behavior<Canvas>
{
   private Point currentMousePosition;

   public ParticlesBehavior()
   {
      this.ShowParticles = new ActionCommand(this.OnShowParticles);
   }

   protected override void OnAttached()
   {
      base.OnAttached();
      AssociatedObject.MouseMove += new MouseEventHandler(AssociatedObject_MouseMove);
   }

   protected override void OnDetaching()
   {
      base.OnDetaching();
      AssociatedObject.MouseMove -= new MouseEventHandler(AssociatedObject_MouseMove);
   }

   void AssociatedObject_MouseMove(object sender, MouseEventArgs e)
   {
      currentMousePosition = e.GetPosition(null);
   }

   public ICommand ShowParticles
   {
      get;
      private set;
   }

   private void OnShowParticles()
   {
      ParticleControl p = new ParticleControl();
      p.OffsetX = currentMousePosition.X;
      p.OffsetY = currentMousePosition.Y;
      AssociatedObject.Children.Add(p);
   }
}

 

5. VS里编译后回到Blend,在Assets->Behavior 中将会看到ParticlesBehavior 选项,将ParticlesBehavior 加入LayoutRoot中:

beh

点击Triggers右侧的“+”按钮添加新EventTrigger;点击EventTrigger将SourceName设为staplerPath,EventName设为MouseLeftButtonDown;再次点击“+”为可为其他物品添加ParticlesBehavior特效。另,在ParticlesBehavior.cs中增加一些代码,便可出现下图中Particles Properties设置窗口(详情可下载源代码):

setting

6. 在Blend中F5,点击图片中的订书器(Stapler)便会出现粒子效果(但其不会自动消失),再点击Candies也会出现粒子效果,问题是所有的粒子效果仍然不能消失。打开ParticleControl.xaml.cs 进行编辑: 
    a. 在ParticleControl 类中定义inttotalParticlesCreated
    b. 将this.particles.Count 替换为totalParticlesCreated 
    c. 在SpawnParticle方法最后添加totalParticlesCreated++
至此粒子效果就会自动消失了。

 

7. 最后为staplerPath添加RemoveElementAction,目的是为了每个物品只能点击一次:

remove

removelist

将SourceName 和TargetName 都设置为staplerPath,EventName依然为MouseLeftButtonDown:

removetrigger

源代码下载:

posted @ 2010-01-02 17:12  Gnie  阅读(5409)  评论(5编辑  收藏  举报
Copyright © 2010 Gnie