<< Chapter < Page | Chapter >> Page > |
Except for the call to the DirectionVector method, the code in Listing 14 is straightforward and should not require an explanation beyond the embedded comments. I will explain the DirectionVector method shortly.
Listing 15 uses essentially the same code to instantiate and set the property values on the power pill sprites and the UFO sprites.
Listing 15 . Instantiate and set properties on the power pills and the UFOs.
//Use the same process to instantiate all of the
// power pills and cause them to move from right// to left, top to bottom.
for(int cnt = 0;cnt<numPills;cnt++) {
pills.Add(new Sprite("ball",Content,random));pills[cnt].Position = new Vector2((float)(windowWidth * random.NextDouble()),
(float)(windowHeight * random.NextDouble()));pills[cnt].Direction = DirectionVector((float)maxVectorLength,
(float)(maxVectorLength * random.NextDouble()),true,//xNeg
false);//yNegpills[cnt].WindowSize =new Point(windowWidth,windowHeight);
pills[cnt].Speed = maxPillSpeed/2
+ maxPillSpeed * random.NextDouble()/2;}//end for loop
//Use the same process to instantiate all of the// ufos and cause them to move from right to left,
// bottom to top.for(int cnt = 0;cnt<numUfos;cnt++) {
ufos.Add(new Sprite("ufo",Content,random));ufos[cnt].Position = new Vector2((float)(windowWidth * random.NextDouble()),
(float)(windowHeight * random.NextDouble()));ufos[cnt].Direction = DirectionVector((float)maxVectorLength,
(float)(maxVectorLength * random.NextDouble()),true,//xNeg
true);//yNegufos[cnt].WindowSize =new Point(windowWidth,windowHeight);
ufos[cnt].Speed = maxUfoSpeed/2
+ maxUfoSpeed * random.NextDouble()/2;}//end for loop
}//end LoadContent
The DirectionVector method shown in Listing 16 is called each time the code in Listing 14 and Listing 15 needs to set the Direction property on a sprite. This method is declared private because it has no meaning outside the Sprite class.
Listing 16 . The private DirectionVector method.
private Vector2 DirectionVector(float vecLen,
float xLen,Boolean negX,
Boolean negY){Vector2 result = new Vector2(xLen,0);
result.Y = (float)Math.Sqrt(vecLen*vecLen- xLen*xLen);
if(negX)result.X = -result.X;
if(negY)result.Y = -result.Y;
return result;}//end DirectionVector
The DirectionVector method returns a direction vector as type Vector2 given the length of the vector, the length of the X component of the vector, the sign of the X component, and the sign of the Ycomponent.
You should set negX and/or negY to true to cause them to be negative.
By adjusting the signs on the X and Y components, the vector can be caused to point into any of the four quadrants. The relationships between these two valuesand the direction of motion of the sprite are as follows:
Notification Switch
Would you like to follow the 'Xna game studio' conversation and receive update notifications?