Track to enemy in vision cone using near sensor and sort by disance (upbge 0.2.5 and 0.3.0)

lerp_target_cone_edit_2_8_plus.blend (637.6 KB)

lerp_target_cone_edit.blend (527.5 KB)

ezgif.com-video-to-gif (12)

import bge
from mathutils import Vector
cont = bge.logic.getCurrentController()


own = cont.owner


def main():
    NL =[]
    near = cont.sensors['Near']
    if near.positive:
        #the near sensor hit something
        for obj in near.hitObjectList:
            local = own.worldTransform.inverted() * obj.worldPosition
            if local.x>0 and abs(local.y)-local.x<0 and abs(local.z)-local.x<0:
                #target is inside vision cone
                NL.append( (obj, local.magnitude) )
        
        #sort viable targets by distance
        if len(NL)>1:
            NL.sort(key=lambda x:x[1])
        
        if len(NL)>0:
            target = NL[0][0]
            #Empty moves 1/4 of the way to target each frame
            
            own.children['Target_Empty'].worldPosition = own.children['Target_Empty'].worldPosition.lerp(target.worldPosition, .25)
        else:
            #Empty moves 1/4 of the way to resting position
            pos = own.worldTransform * Vector([6,0,0])
            own.children['Target_Empty'].worldPosition = own.children['Target_Empty'].worldPosition.lerp(pos, .25)
                    
    else:
        #Empty moves 1/4 of the way to resting position
        pos = own.worldTransform * Vector([6,0,0])
        own.children['Target_Empty'].worldPosition = own.children['Target_Empty'].worldPosition.lerp(pos, .25)
main()
        
4 Likes

Really cool, gonna study these, thanks a lot!