'Track to' via python

Hi all, I know I could just use a ‘track to’ actuator but I wanna know how to do it with python.

I tried this:

cont = bge.logic.getCurrentController()
own = cont.owner


sens = cont.sensors['Always']

scene = bge.logic.getCurrentScene()
target = scene.objects ["blue"]


if sens.positive:
    vec = own.getVectTo(target.name)
    own.alignAxisToVect(vec,1,1.0)

It sends an error: AttributeError: one or more of the items in the sequence was not a float

Attachments

track_to_python.blend (637 KB)

1 is not a float
1.0 is a float

Thanks Monster, I guess…, but I still don’t know why it won’t work.

this return 1 float and 2 vectors:
vec = own.getVectTo(target.name)

this should work
vec = own.getVectTo(target.name)[1]

PS: if the distance is 0.0 (improbable but possible overall with objects statics)
you can get a error
i suggest to write this way:


cont = bge.logic.getCurrentController()
own = cont.owner


sens = cont.sensors['Always']

scene = bge.logic.getCurrentScene()
target = scene.objects ["blue"]


if sens.positive:
    distance, vec_global, vec_local = own.getVectTo(target.name)
    if distance > 0.0:
        own.alignAxisToVect(vec_global,1,1.0)



MarcoIT, you’re the man! Thanks.

@@helluvamesh, you can also access the list like this after your assignment


vec = own.getVectTo(target.name)
own.alignAxisToVect(<b>vec[1]</b>,1,1.0)

My idea when I did a track-to-nearest was to make the player track to an empty, that just moves to the position of the nearest enemy whenever they’re close/player’s aiming.

That way, you get the smooth turning that the actuator gives you, rather than a quick rotation. I did it this way purely because as far as I know, you can’t modify the track-to actuator’s object via python at this moment.

Probably not the best way to do it but it works, and it gives you a very good looking result. Plus it’s very easy to use :stuck_out_tongue:

Pete

you get the smooth turning that the actuator gives you, rather than a quick rotation

you can get smooth rotation with alignAxisToVect() as well. The last value is speed of turning to the alignment. 0.0(none)-1.0(instant)

You might also want to tack another alignAxisToVect() to keep your character pointing upright.

own.alignAxisToVect( (0,0,1), 2, 1.0 )

This keeps your positive Z axis aligned with the world’s positive Z axis, and will keep your character from rolling/tilting inappropriately while trying to track.

This is the equivalent of defining the “Up Axis” for the track-to actuator.

Oh is it! Well, you learn something new every day :slight_smile:

I use my actors Z axis as my second reference many times

player.worldOrientation.col[2] = Z axis vector

I posted something similar on this thread: 3D and 2D track to point with proper interpolation in Python Solution
Hope it helps here! :wink: