AbsolutePickle42
AbsolutePickle42

Reputation: 61

Player not looking in the right direction

I have a player that you can move by clicking in a location. They are guided by pathfinding to also move around any potential obstacles in their way. Here is my script:

extends KinematicBody2D

export var speed = 200
var velocity = Vector2.ZERO

onready var navigation_agent = $NavigationAgent2D

func _ready():
    navigation_agent.connect("velocity_computed", self, "move")

func _input(event):
    if event.is_action_pressed("mouse_right"):
        navigation_agent.set_target_location(event.get_global_position())

func _process(_delta):
    if $RayCast2D.is_colliding():
        if $RayCast2D.get_collider().is_in_group("enemy_ground_troop"):
            self.velocity = Vector2.ZERO
            ranged_attack()

    if navigation_agent.is_navigation_finished():
        return

    var overlapping_areas = $EnemyDetector.get_overlapping_areas()

    for area in overlapping_areas:
        if area.is_in_group("enemy_ground_troop"):
            navigation_agent.set_target_location(area.get_global_position())
            look_at(area.get_global_position())
    
    velocity = global_position.direction_to(navigation_agent.get_next_location()) * speed

    look_at(global_position.direction_to(navigation_agent.get_next_location()))
    $RayCast2D.global_rotation = self.global_rotation

    navigation_agent.set_velocity(velocity)

func move(velocity):
    velocity = move_and_slide(velocity)

func ranged_attack():
    print_debug("fired ranged attack")

When I run the scene, the player is not looking where I want them too based on the look at commands. How can I fix this?

Upvotes: 0

Views: 118

Answers (1)

Theraot
Theraot

Reputation: 40200

The look_at method takes a target position, not a direction.

So, instead of this:

look_at(global_position.direction_to(navigation_agent.get_next_location()))

Try this:

look_at(navigation_agent.get_next_location())

Upvotes: 0

Related Questions