Table of Contents

Introduction

This is an example of how to move an object in a given direction, by a given distance.

Sample Code

    Public Function MoveVector(ByVal Direction As TV_3DVECTOR, ByVal Distance As Single) As TV_3DVECTOR
        Dim NewPosition As TV_3DVECTOR
        Dim vTheta As Single = Math3D.Deg2Rad(Direction.x)
        Dim hTheta As Single = Math3D.Deg2Rad(Direction.y)
        NewPosition.y = Distance * Sin(vTheta)
        NewPosition.x = Distance * Cos(vTheta) * Cos(hTheta)
        NewPosition.z = Distance * Cos(vTheta) * Sin(hTheta)
        Return NewPosition
    End Function

Usage

Instead of taking 2 angles for the direction of travel, this sample uses a 3D vector. The direction is then converted to an angle (internally) and the resulting vector is output.

The code can be used in 2 different ways. Firstly it can be used to simply move an object by taking its existing position and adding the movement vector to it.

    Dim mPos as TV_3DVECTOR
    mPos = myMesh.GetPosition()
    mPos = Math3D.VAdd(mPos,MoveVector(mDirection,mSpeed))
    myMesh.SetPosition(mPos)

Or secondly, you can use it with TVPhysics to apply a force to an object.

    Dim ForceVectorFW As TV_3DVECTOR
    Dim ForceVectorLR As TV_3DVECTOR
    Dim ForceVectorTotal As TV_3DVECTOR
 
    ForceVectorFW = MoveVector(New TV_3DVECTOR(0, _CamRotH, 0), AmountUD)
    ForceVectorLR = MoveVector(New TV_3DVECTOR(0, _CamRotH + 90, 0), AmountLR)
    ForceVectorTotal = Math3D.VAdd(ForceVectorFW, ForceVectorLR)
        
    Physics.SetForce(PlayerPhy, ForceVectorTotal)

In this example, I am taking a Camera Angle (_CamRotH), a Forward/Backward distance (AmountUD) and a Left/Right distance (AmountLR). By adding the resulting vectors together, you can apply a force to an object that is relative to the camera angle. AmountLR and AmountUD in this example where being obtained from the input of a gamepad. With the Y axis mapped to AmountUD and the X axis mapped to AmountLR.

Summary

It’s not always the best way of doing things. There are situations where it would be better to take a pair of angles instead of a direction vector, but this particular method is well suited to easily taking input from gamepads/joysticks/etc.

Have Fun!

PhonicUK

 
tutorialsarticlesandexamples/moving_in_a_given_angle.txt · Last modified: 2013/11/22 13:32