Rotate around Object (Part 1)

I noticed many people ask how to rotate the camera about an object. Well, I decided to help you guys. In part 1 we will treat a normal rotation on the Y-axis (we set the x and z position). I’ll use VB.Net, because it’s easily portable to both C# and VB6. I also use radians instead of degrees, I don’t know why but you should be easily able to convert it to work with degrees.

First some maths. We’re going to use the formula

x(t) = cos(t) * r
y(t) = sin(t) * r

This code is able to compute any position within radius ‘r’. where ‘t’ represents our time unit. X and Y represent the resulting positions. The reason why it produces a circle is a bit complex and the answer lies inside cosinus and sinus.

We will only need a few objects. A TVEngine, TVMesh and a TVScene. Let’s declare them

Dim tv As TrueVision3D.TVEngine
Dim scene As TrueVision3D.TVScene
Dim mesh As TrueVision3D.TVMesh

We also need some vars for our maths.

Dim t As Single
Dim x As Single
Dim y As Single
Dim Const r As Single = 9

t=time unit x=pos x returned by cos(t) * r y=pos z returned by sin(t) * r r=radius

Ok, now do some initialization

'init tv
tv = New TrueVision3D.TVEngine
tv.SetAngleSystem(TrueVision3D.CONST_TV_ANGLE.TV_ANGLE_RADIAN)
tv.Init3DWindowedMode(Me.Handle)
tv.DisplayFPS = True
 
'init scene
scene = New TrueVision3D.TVScene
scene.GetCamera.SetLookAt(0, 0, 0)
 
'create the mesh
mesh = scene.CreateMeshBuilder("teapot")
mesh.CreateTeapot()

You should be able to understand everything above. Now we’re going to write the render loop:

Do While True
    tv.Clear()
 
    'render our teapot
    mesh.Render()
 
    t = t + (tv.TimeElapsed / 814)
 
    'calculate new values for x and z
    ' var x = pos z
    ' var y = pos x
 
    x = Math.Cos(t) * r
    y = Math.Sin(t) * r
 
    'set camera
    scene.GetCamera.SetPosition(y, 0, x)
    scene.GetCamera.SetLookAt(0, 0, 0)
 
    tv.RenderToScreen()
 
    Application.DoEvents()
Loop

the really important lines are these two:

x = Math.Cos(t) * r
y = Math.Sin(t) * r

these describe the formula which is handled above. It takes the cosinus of out ‘time unit’, and multiplies it by the radius. Later we assign them to our X and Z position of the camera. After that we reset the camera lookat to the coord (0,0,0), so it keeps looking at the same spot.

also very important is this line:

t = t + (tv.TimeElapsed / 814)

it calculates the incremental of ‘t’ (tv.TimeElapsed / 814), and than adds it to ‘t’. The value 814 is calculated by me, it represents a fast rotation. You may need some tweaking here.

When you run the code you’ll find yourself spinning around a white teapot. Interesting.

 
tutorialsarticlesandexamples/turntabling_the_camera_around_an_object.txt · Last modified: 2007/07/30 20:40