1: using System;
2: using Microsoft.Xna.Framework;
3:
4: namespace GameUtilities
5: { 6: public class LinearPathHelper
7: { 8: private Vector2 _startPoint;
9: private Vector2 _endPoint;
10: private float _lineSlope = 0.0f;
11: private float _yIntercept = 0.0f;
12: private float _xIntercept = 0.0f;
13: private Ray _direction;
14:
15: private StopRegion _stopRegion;
16:
17: public LinearPathHelper(Vector2 startPoint, Vector2 endPoint, float speed)
18: { 19: _startPoint = startPoint;
20: _endPoint = endPoint;
21:
_lineSlope = (_endPoint.Y - _startPoint.Y) / (_endPoint.X - _startPoint.X); 22:
23: if (float.IsNegativeInfinity(_lineSlope) || float.IsInfinity(_lineSlope)) //vertical line moving down
24: { 25: if (_startPoint.Y > _endPoint.Y)
26: _yIntercept = -speed;
27: else
28: _yIntercept = speed;
29:
30: _xIntercept = 0.0f;
31: }
32: else if (float.IsNaN(_lineSlope)) //vertical line moving up
33: { 34: if (_startPoint.Y > _endPoint.Y)
35: _yIntercept = -speed;
36: else
37: _yIntercept = speed;
38:
39: _xIntercept = 0.0f;
40: }
41: else //diagonal line
42: { 43: _yIntercept = (_lineSlope * _endPoint.X) * speed;
44: _direction = new Ray(new Vector3(_startPoint,0.0f),new Vector3( _endPoint,0.0f));
45: _xIntercept = _direction.Direction.X * speed;
46: }
47:
48: _stopRegion = new StopRegion(_endPoint, 10f, 10f);
49: _stopRegion.Inflate(speed);
50:
51: }
52:
53: private class StopRegion
54: { 55: private float _top;
56: private float _bottom;
57: private float _left;
58: private float _right;
59:
60: public StopRegion(Vector2 point, float width, float height)
61: { 62: _top = point.Y - (height / 2);
63: _left = point.X - (width / 2);
64:
65: _bottom = point.Y + height;
66: _right = point.X + width;
67: }
68:
69: public void Inflate(float size)
70: { 71: if (size < 1)
72: size = 50;
73:
74: _top -= size;
75: _bottom += size;
76: _left -= size;
77: _right += size;
78: }
79:
80: public bool VectorInRect(Vector2 position)
81: { 82: return (position.X >= _left && position.X <= _right &&
83: position.Y >= _top && position.Y <= _bottom);
84: }
85: }
86:
87: public void MoveVectorPoint(ref Vector2 currentPointPos)
88: { 89: //if we are within the boundaries of our stopping region - we need to snap to it
90: //so the move helper will stop the animation timer...
91: if (_stopRegion.VectorInRect(currentPointPos))
92: { 93: currentPointPos = _endPoint;
94: return;
95: }
96:
97: currentPointPos.X -= _xIntercept;
98: currentPointPos.Y -= _yIntercept;
99: }
100:
101: public bool IsAtDestination(Vector2 currentPointPos)
102: { 103: return currentPointPos == _endPoint;
104: }
105: }
106: }