0
$\begingroup$

I have the following code:

import bge
from bge import logic

controllor = bge.logic.getCurrentController()
scene = bge.logic.getCurrentScene()

target = scene.objects['Target']
ray = controllor.sensors['Ray']

if (ray.hitObject and not 'Fire_False' in ray.hitObject):
    target.worldPosition = ray.hitPosition

This works fine wit all my weapons except melees. The reason for that is the following: bullet holes are added to the target, as that is where the bullet actually is. For melees, you can use a melee in a short range, as in, when you attack, you only attack close. I need to edit this script into where if it [target] is not colliding with anything, a property will be false. The property, if false, means that it [target] should be tracking to an object. How can I achieve this? Any help is appreciated. Thanks!

ALSO: For ease, I just need a prop to be false when not colliding.

$\endgroup$
4
$\begingroup$

If all you want to do is change a property called "hit":

import bge  
cont = bge.logic.getCurrentController()
ray = cont.sensors['Ray']
if not ray.hitObject:
    cont.owner['hit'] = False
elif ray.hitObject and not 'Fire_False' in ray.hitObject:
    cont.owner['hit'] = True

Here is the full code to move your target object to the location of the ray hit or the closest melee enemy.
You will need to add an Always sensor with true level triggering, plugged in to your script along with the ray sensor. Add a game property to all of your melee enemies called "melee_target."

import bge

cont = bge.logic.getCurrentController()
scene = bge.logic.getCurrentScene()

target = scene.objects['Target']

allMelee = [o for o in scene.objects if "melee_target" in o]
allMelee.sort(key=lambda o: cont.owner.getDistanceTo(o))

ray = cont.sensors['Ray']
if not ray.hitObject:
    target.worldPosition = allMelee[0].worldPosition
elif ray.hitObject and not 'Fire_False' in ray.hitObject:
    target.worldPosition = ray.hitPosition

First the simple part if not ray.hitObject means if the ray is not hitting anything.

The allMelee variable line is looping through all the objects in the scene and if they have the property of melee_target then they are added to the "allMelee" list.

allMelee.sort(key=lambda o: cont.owner.getDistanceTo(o)) is sorting the list of melee enemies in the order of closest to farthest away from the object the script is on.

Last thing to do is move the target object to that location of the closest melee, that is done with this line
target.worldPosition = allMelee[0].worldPosition.
allMelee[0] is taking the first object out of the list (and thus the closest)

Thank you to Goran Milovanovic who first showed me how to get and sort a list of game objects.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.