Making an AI "zig zag" toward player

HanskHansk Posts: 6Member

Hello, I would like to make my AI enemy zig zag as it moves toward the player after it sees them. I have a function that proves if it is allowed to move, find the direction of the player, then moves toward them. However, as the enemy moves toward the player I would like it to make a short pause then move toward the player but at an oblique angle. My only idea so far is to generate a random number then someone add/subtract it to the rotation angle of the enemy on the Y axis, but it's not working out for me since you can't add integers to Vector3 numbers. Here is my function so far:

func move_to_target(delta):
    if move == true:
        while i < 3:
            var r = RandomNumberGenerator.new()
            r.randomize()
            var mrn = r.randi_range(-30, 30)
            move_and_slide(direction * speed * delta, Vector3.UP)
            yield(get_tree().create_timer(pause), "timeout")
            i = i + 1 
            state = ALERT

I would like to add a line after the timer for the new direction. I'm very new so if there is a better/more obvious way to do this I'm all ears.

Thank you.

Answers

  • vinpogovinpogo Posts: 33Member

    one idea: generate an Array holding the positions of the zigzag path. Then let the enemy simply go from one point to the next.

    How to generate that Array:
    1. get position of player
    2. between enemy position and player position generate X points (=supportPoints), where X = (playerPosition - position) / zigzagIntervalLength
    3. for each of those newly created points translate them by Y, where Z = supportPoint + (playerPosition - supportPoint).normal * zigzagAmplitude * (-1)^supportPointIndex

    So the idea is that you control the zigzagPath with 2 parameters, zigzagIntervalLength & zigzagAmplitude.

    zigzagIntervalLength: used to control the distance between the zigzagPoints.
    zigzagAmplitude: used to control the 'zigzaginess' of the line. smaller value leads to a more straight line.

    this should give you a zigzagPath from enemyPosition to playerPosition. What i did not consider in this approach is the moving player. So you will need to recalculate them regularly for your enemy to finally reach the player.

  • HanskHansk Posts: 6Member

    Oh that's a good idea! Thing is I understand the concept but may have trouble parsing the code, however, I'll take a swing at it.

    Thank you!

Leave a Comment

BoldItalicStrikethroughOrdered listUnordered list
Emoji
Image
Align leftAlign centerAlign rightToggle HTML viewToggle full pageToggle lights
Drop image/file