<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Silverlight &#124; WPF &#124; Microsoft.Net &#187; Deflection</title>
	<atom:link href="http://joel.neubeck.net/tag/deflection/feed/" rel="self" type="application/rss+xml" />
	<link>http://joel.neubeck.net</link>
	<description>Simplifing structure without changing results</description>
	<lastBuildDate>Fri, 01 Apr 2011 21:34:22 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.1</generator>
		<item>
		<title>Spherical elastic and inelastic collisions in Silverlight</title>
		<link>http://joel.neubeck.net/2008/05/spherical-collisions/</link>
		<comments>http://joel.neubeck.net/2008/05/spherical-collisions/#comments</comments>
		<pubDate>Wed, 21 May 2008 21:51:40 +0000</pubDate>
		<dc:creator>joel</dc:creator>
				<category><![CDATA[Microsoft]]></category>
		<category><![CDATA[Silverlight]]></category>
		<category><![CDATA[animation]]></category>
		<category><![CDATA[code]]></category>
		<category><![CDATA[Deflection]]></category>
		<category><![CDATA[Elastic Collision]]></category>
		<category><![CDATA[Inelastic Collision]]></category>
		<category><![CDATA[Physics]]></category>

		<guid isPermaLink="false">http://joel.neubeck.net/2008/05/spherical-collisions/</guid>
		<description><![CDATA[I recently took an interest in using some very basic physics within Silverlight 2. I took physics nearly 12 years ago and am certainly rusty, but thought it would be fun to simulate he effect two spheres have when they collide. Their are two types of collision; a perfectly elastic collision where there is no [...]]]></description>
			<content:encoded><![CDATA[<p>I recently took an interest in using some very basic physics within Silverlight 2. I took physics nearly 12 years ago and am certainly rusty, but thought it would be fun to simulate he effect two spheres have when they collide. Their are two types of collision; a perfectly elastic collision where there is no lose in kinetic energy and an inelastic collision where some or all of the kinetic energy is converted into internal energy.&nbsp;&nbsp; In the example below I try to demonstrate both types of collision along with a form of inelastic collision I call magnetic where upon collision energy is transferred in the direction of the collision and the sphere attaches itself to the object it is colliding with.
<p><iframe src="/wp-content/uploads/2008/05/SphericalCollision/default.html" width="450" height="450"></iframe></p>
<p>I am pretty certain I am taking some liberties with accuracy of each collision, but nonetheless one can see the effect two spheres have on momentum.&nbsp; Interestingly, if you allow the demo to run long enough most if not all of the balls will stop colliding. The first thing I needed to do to create my sample was to create a UserControl that would represent my sphere. Within this control I created a series of properties and two public Method: &#8220;Move()&#8221; and &#8220;Collision()&#8221;. Since each sphere will move through my container the same way, I can encapsulate this logic within the control itself. Here is that code.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
</pre></td><td class="code"><pre class="c-sharp" style="font-family:monospace;">public void Move(Rect bounds)
{
    //add the current vector to each X/Y 
    this.X += this.VX;
    this.Y += this.VY;
&nbsp;
    //check to see if this sphere has collided with an adjacent wall
    //if so, then reverse its vector.  Since my bounding box is definable 
    //pass in a Rect struct
&nbsp;
    //check the left and the right of the bound box
    if (this.X &amp;lt; bounds.X &amp;amp;&amp;amp; this.VX &amp;lt; 0)
        this.VX = -this.VX;
&nbsp;
    if(this.X &amp;gt; (bounds.Right-this.Distance) &amp;amp;&amp;amp; this.VX &amp;gt; 0)
        this.VX = -this.VX;
&nbsp;
    //check the top and the bottom
    if (this.Y &amp;lt; bounds.Y &amp;amp;&amp;amp; this.VY &amp;lt; 0)
        this.VY = -this.VY;
&nbsp;
    if(this.Y &amp;gt; (bounds.Bottom-this.Distance) &amp;amp;&amp;amp; this.VY &amp;gt; 0)
        this.VY = -this.VY;
&nbsp;
    //move this sphere to its new X,Y position
    _translate.X = this.X;
    _translate.Y = this.Y;
}</pre></td></tr></table></div>

<p>Since my container floats in the center of my Page.xaml I use a &#8220;Rect&#8221; struct to hold the X,Y, Width and Height of the UIElement that that will confine the spheres. I pass this &#8220;Rect&#8221; as an argument. Depending on the surface that the object is colliding with, I move the sphere and reverse the vector by either adding or subtracting itself from VX or VY. In addition to determining how itself moves, the sphere I also determines the effect of a collision. This method is pretty big, but is broken down into four sections. The first determines the time in which the two spheres collide where is the remaining determine the effect of each type of collision.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
</pre></td><td class="code"><pre class="c-sharp" style="font-family:monospace;">public bool Collision(Sphere s)
{
    // find the time when the two spheres really collide with each other.
    double dx = (this.X + this._radius) - (s.X + s.Radius);
    double dy = (this.Y + this._radius) - (s.Y + s.Radius);
&nbsp;
    //calculate the distance between two balls 
    double distance = dx * dx + dy * dy;
    double distanceSqrt = Math.Sqrt(distance);
&nbsp;
    double dvx = this.VX - s.VX;
    double dvy = this.VY - s.VY;
&nbsp;
    if (distanceSqrt &amp;gt; (this._radius + s.Radius))
        return false;
    //There are two basic kinds of collisions, elastic and inelastic:
    //if an elastic collision occurs send both spheres rebounding backwards
    //with no loss in total kinetic energy.
&nbsp;
    //Note: since both of our spheres have the same mass the only way to determine 
    //which type of collision will occur is to look at velocity.
    double collision = 0.0;
    if (this.CollisionType == CollisionTypes.Elastic || 
	s.CollisionType == CollisionTypes.Elastic)
    {
        collision = dvx * dx + dvy * dy;
        if (collision &amp;gt; 0)
            return false;
&nbsp;
        collision /= distance;
&nbsp;
        double deltaVX = dx * collision;
        double deltaVY = dy * collision;
&nbsp;
        //deflect this sphere
        this._vx -= deltaVX;
        this._vy -= deltaVY;
        //deflect the sphere that was part of the collision
        s.VX += deltaVX;
        s.VY += deltaVY;
    }
    //if a partial inelastic collision occurs the spheres collide and some 
    //kinetic energy is lost...both masses decelerate
    else if(this.CollisionType == CollisionTypes.Inelastic || 
	s.CollisionType == CollisionTypes.Inelastic)
    {
        collision = dvx * dx + dvy * dy;
        if (collision &amp;gt; 0)
            return false;
&nbsp;
        collision /= distance*2;
&nbsp;
        double deltaVX = dx * collision;
        double deltaVY = dy * collision;
&nbsp;
        //deflect this sphere
        this._vx -= deltaVX;
        this._vy -= deltaVY;
        //deflect the sphere that was part of the collision
        s.VX += deltaVX;
        s.VY += deltaVY;
    }
    //if a magnetic collision occurs we would have a perfectly inelastic collision
    else if (this.CollisionType == CollisionTypes.Magnetic &amp;amp;&amp;amp; 
	s.CollisionType == CollisionTypes.Magnetic)
    {
        //the sphere causing the collision will continue its forward momentum 
        //attaching itself to the adjacent sphere
        s.VX = this.VX;
        s.VY = this.VY;
    }
    return true;
}</pre></td></tr></table></div>

<p>Code: <a onclick="javascript: pageTracker._trackPageview('/code/SphericalCollision.zip');" href="/wp-content/uploads/2008/05/SphericalCollision/SphericalCollision.zip">SphericalCollision.zip</a></p>
]]></content:encoded>
			<wfw:commentRss>http://joel.neubeck.net/2008/05/spherical-collisions/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Silverlight Circular Collision Animation</title>
		<link>http://joel.neubeck.net/2008/05/silverlight-circular-collision-animation/</link>
		<comments>http://joel.neubeck.net/2008/05/silverlight-circular-collision-animation/#comments</comments>
		<pubDate>Wed, 14 May 2008 19:34:55 +0000</pubDate>
		<dc:creator>joel</dc:creator>
				<category><![CDATA[Microsoft]]></category>
		<category><![CDATA[Silverlight]]></category>
		<category><![CDATA[animation]]></category>
		<category><![CDATA[Circular Rotation]]></category>
		<category><![CDATA[code]]></category>
		<category><![CDATA[Collision]]></category>
		<category><![CDATA[Deflection]]></category>
		<category><![CDATA[DispatcherTimer]]></category>
		<category><![CDATA[RotateTransform]]></category>
		<category><![CDATA[TranslateTransform]]></category>

		<guid isPermaLink="false">http://joel.neubeck.net/2008/05/silverlight-circular-collision-animation/</guid>
		<description><![CDATA[Building on the sample I created on Circular Motion, in this example I add a concept of collision.&#160; In physics, deflection is the event that occurs where an object collides and bounces off of another surface.&#160; In my example, two spheres collide at a given X/Y causing each ball to reverse direction and maintains its [...]]]></description>
			<content:encoded><![CDATA[<p>Building on the sample I created on <a href="/2008/05/silverlight-circular-motion-animation/">Circular Motion</a>, in this example I add a concept of collision.&nbsp; In physics, deflection is the event that occurs where an object collides and bounces off of another surface.&nbsp; In my example, two spheres collide at a given X/Y causing each ball to reverse direction and maintains its current speed and angle.</p>
<p><iframe src="/wp-content/uploads/2008/05/CircularCollision/default.html" width="300" height="300"></iframe></p>
<p>Just as in my previous example I use a single DispatcherTimer and a generic collection of UserConrols. To keep track of the direction that each ball is traveling I added a boolean property to my &#8220;Ball&#8221; user control to determine if it was rotating clockwise.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
</pre></td><td class="code"><pre class="c-sharp" style="font-family:monospace;">void _timer_Tick(object sender, EventArgs e)
{
    foreach (Ball ball in _balls)
    {
        double x = 0.0;
        double y = 0.0;
        double angle = ball.Rotate.Angle;
&nbsp;
        CalculatePosition(ball.Clockwise, ref x, ref y, ref angle, 1);
        //update the position of the ball
        ball.Rotate.Angle = angle;
        ball.Translate.X = x;
        ball.Translate.Y = y;
&nbsp;
        //check to see if a collision has occured
        if (ball.CollisionType == Ball.CollisionTypes.Deflect)
        {
            foreach (Ball ball2 in _balls)
            {
                if (!ball.Equals(ball2))
                {
                    double b2X = 0.0;
                    double b2Y = 0.0;
                    double b2A = ball2.Rotate.Angle;
                    //if we wait until the two balls are at the same X/Y then the balls
                    //will have overlapped.  Instead, predict by looking 5 degrees ahead 
                    //then switching direction.
                    CalculatePosition(ball2.Clockwise, ref b2X, ref b2Y, ref b2A, 5);
                    if (Math.Ceiling(x).Equals(Math.Ceiling(b2X))
                        &amp;amp;&amp;amp; Math.Ceiling(y).Equals(Math.Ceiling(b2Y)))
                    {
                        ball.Clockwise = !ball.Clockwise;
                        ball2.Clockwise = !ball2.Clockwise;
                        //ball.sound.Position = TimeSpan.FromMilliseconds(0);
                        //ball.sound.Play();
                        break;
                    }
                }
            }
        }
    }
}</pre></td></tr></table></div>

<p>As you can see in the code above, I am doing a quick check to see if my rotating ball is defined to deflect upon collision. In this example, this is the only type of collision supported. In the future, I might add things like exploding on impact or magnetism upon the collision. </p>
<p>The first step in the circular rotation is to move each ball to its new X/Y position. Once moved, I check to see if any other balls overlap its current X/Y location. To make the collision more realistic (no overlap), I predict where each additional ball will exist 5 degrees forward of its current angle. This allows me to simulate the ball just touching each other before reversing directions. </p>
<p>Code: <a onclick="javascript: pageTracker._trackPageview('/code/CircularCollision.zip');" href="/wp-content/uploads/2008/05/CircularCollision/CircularCollision.zip">CircularCollision.zip</a></p>
]]></content:encoded>
			<wfw:commentRss>http://joel.neubeck.net/2008/05/silverlight-circular-collision-animation/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>

