Track to closest

Track to closest object containing ‘Player’

Mario cart style RedShell


import bge


cont=bge.logic.getCurrentController()


own=cont.owner


if 'Init' not in own:
    own['Target']="Empty"
    D=40
    scene=bge.logic.getCurrentScene()
    for item in scene.objects:
       if 'Player' in item:
           Dist=own.getDistanceTo(item)
           if Dist<D:
              own['Target']=item
              D=Dist
       own['Init']=True
       print(own['Target'])
else:
    
    if own['Target']!="Empty":
        x=own.getVectTo(own['Target'])
        own['TargetName']=own['Target'].name
        own.alignAxisToVect(x[1],1,.5)
        own.alignAxisToVect((0,0,1),2,1)
        own.applyForce((0,10,0),1)
 

I chose this design, so that it would not iterate through all objects each frame, saving cpu,by only iterating one time on spawn, this could be rethought out and track to nearest by building a list, and then iterating each frame through a smaller list then scene.objects

the only way I can think of making it leaner, would be to use the track to actuator on 2d mode, and just feed it the target, however, if the target dies, the track to will throw a error, so… I chose slightly more logic per frame, so that in the end it was fault tolerant.

Attachments

RedShell (1).blend (465 KB)

Without your blend files i would have never understood as a beginner thank u very much :slight_smile:

You should add comments too.

Good idea :smiley:


These comments are not necessary. Comments that repeat the code do not add any additional value and after a few updates they quickly do not match the code anymore.

It would look better if you put a space between the # and the begin of the text rather than another #.

You mix upper case and lower case variable names. Better stay consistent.

Calling an vector “x” is irritating. “x” is a typical term for a single axis of a vector (x,y,z). If you mean a vector along X you can call it xAxis.

The code snippet is full of hard-coded parameters. This forces any user to modify the code to fit the custom situation. It is not good for a ready to use code snippet.

It is fine if you want to demonstrate a concept. But you should add some explanations what the context is (objects, sensors, properties etc.), what happens, why you choose exactly this design. You can do that via comments or in this thread.

I hope it helps

X=(M*V^2)/R

it’s just left over from algebra class , I’ll try and brake the habit.