11/15/07

VB.NET XNA Tutorial 6: The PointAt method

[GSE 1.0 Refresh]

In the comments for tutorial 5.3, Matt asked a practical question about how to solve a real-world problem using all this matrix cascade stuff; if a ship sprite had a "child" gun turret, how could we get that gun turret to aim at some other sprite on the screen?

Here's a method written to accomplish this task, called PointAt. Accepting two sprites as arguments, it will rotate the first in order to point at the second. This will cut through all the matrix clutter by turning that clutter around and using it to our advantage.

 ''' <summary>
 ''' Point one sprite's origin at another sprite's origin
 ''' </summary>
 ''' <param name="thePointer">The sprite you want to rotate</param>
 ''' <param name="theTarget">The sprite you want thePointer to point at</param>
 ''' <remarks></remarks>
 Public Sub PointAt(ByVal thePointer As Sprite, ByVal theTarget As Sprite)

 Dim objTargetWorldPosition As Vector2

 If theTarget.Parent IsNot Nothing Then
 objTargetWorldPosition = Vector2.Transform(theTarget.Location, theTarget.Parent.DrawMatrix)
 Else
 objTargetWorldPosition = theTarget.Location
 End If

 thePointer.Rotation = 0

 With Vector2.Transform(objTargetWorldPosition, Matrix.Invert(thePointer.DrawMatrix)) - thePointer.Origin

 thePointer.Rotation = (CSng(Math.Atan2(.Y, .X)) + (Math.PI / 2))

 End With

 End Sub

It looks simple, doesn't it? There's some new stuff in there (Matrix.Invert?) so I went ahead and made a video demonstrating what this "simple" method does, adding some slight difficulty for the PointAt method to overcome. The PointAt method is nice because it doesn't really care what we throw at it. It should be able to point any sprite at any other sprite, no matter where either sprite is or how far down any given matrix cascade either sprite happens to be.

Here is the link to Tutorial 6: The PointAt method on Vimeo.

In the video, the steps shown in Photoshop for inverting the matrix are oversimplified a little bit; in actuality, inverting the DrawMatrix of the cannon sprite would also involve un-doing the rotation of the PlayersShip (which would require a lot more steps to simulate in PhotoShop) but the net result is the same.

1 comments:

Matt Worden said...

"I've seen the future and it works!" ;-)

That's just plain sexy ... thanks for that example.

I see that my greatest hurdle as I start to orient myself on .Net (and Managed DirectX/XNA) is to understand what built-in functions are available within the various namespaces to handle the heavy lifting. :-/