1: void Spring(Particle a, Particle b)
2: { 3: double dx = b.X - a.X;
4: double dy = b.Y - a.Y;
5:
6: double dist = Math.Sqrt(dx * dx + dy * dy);
7: if (dist < _minDist)
8: { 9: double ax = dx * _spring;
10: double ay = dy * _spring;
11:
12: a.VX += ax;
13: a.VY += ay;
14:
15: b.VX -= ax;
16: b.VY -= ay;
17:
18: Canvas.SetLeft(a, a.X);
19: Canvas.SetTop(a, a.Y);
20:
21: Canvas.SetLeft(b, b.X);
22: Canvas.SetTop(b, b.Y);
23:
24:
25: }
26:
27: Canvas.SetLeft(a, a.X);
28: Canvas.SetTop(a, a.Y);
29:
30: Canvas.SetLeft(b, b.X);
31: Canvas.SetTop(b, b.Y);
32:
33:
34: }
35:
36: VB:
37: PrivateSub Spring(ByVal a As Particle, ByVal b As Particle)
38: Dim dx AsDouble = b.X - a.X
39: Dim dy AsDouble = b.Y - a.Y
40:
41: Dim dist AsDouble = Math.Sqrt(dx * dx + dy * dy)
42: If dist < _minDist Then
43: Dim ax AsDouble = dx * _spring
44: Dim ay AsDouble = dy * _spring
45:
46: a.VX += ax
47: a.VY += ay
48:
49: b.VX -= ax
50: b.VY -= ay
51:
52: Canvas.SetLeft(a, a.X)
53: Canvas.SetTop(a, a.Y)
54:
55: Canvas.SetLeft(b, b.X)
56: Canvas.SetTop(b, b.Y)
57:
58:
59: EndIf
60:
61: Canvas.SetLeft(a, a.X)
62: Canvas.SetTop(a, a.Y)
63:
64: Canvas.SetLeft(b, b.X)
65: Canvas.SetTop(b, b.Y)
66:
67:
68: EndSub
69:
70: And the main animation loop looks like this:
71:
72: C#:
73: void CompositionTarget_Rendering(object sender, EventArgs e)
74: { 75: for (int i = 0; i < _numParticles; i++)
76: { 77: _particles[i].X += _particles[i].VX;
78: _particles[i].Y += _particles[i].VY;
79:
80: Particle p = _particles[i];
81:
82: if (p.X >this.Width)
83: { 84: p.X = 0;
85: }
86:
87: elseif (p.X < 0)
88: { 89: p.X = this.Width;
90: }
91:
92: if (p.Y >this.Height)
93: { 94: p.Y = 0;
95: }
96: elseif (p.Y < 0)
97: { 98: p.Y = this.Height;
99: }
100: }
101:
102:
103: for (int i = 0; i < _numParticles - 1; i++)
104: { 105: var partA = _particles[i];
106: for (int j = i + 1; j < _numParticles; j++)
107: { 108: var partB = _particles[j];
109: Spring(partA, partB);
110:
111: }
112: }
113: }