0 votes

I have created a player detection script so that my enemy walks toward the player, but it only walks down and nowhere else.

extends KinematicBody2D

var speed = 50
var velocity = Vector2()
var player = preload("res://Player.tscn").instance()
var BackEntered = null
var RightEntered = null
var LeftEntered = null
var ForwardEntered = null

func _physics_process(delta):
    velocity = Vector2()
    if BackEntered:
    velocity.y -= speed
elif BackEntered == null:
    velocity.y = 0

if RightEntered:
    velocity.x = speed
elif RightEntered == null:
    velocity.x = 0

if LeftEntered: 
    velocity.x -= speed
elif LeftEntered == null:
    velocity.x = 0

if ForwardEntered:
    velocity.y = speed
elif ForwardEntered == null:
    velocity.y = 0

    velocity.y = 0
    velocity.x = 0

func _process(delta):
    velocity = move_and_slide(velocity)

area entered

func _on_DetectPlayerBack_body_entered(body):
  BackEntered = player
func _on_DetectPlayerRight_body_entered(body):
  RightEntered = player
func _on_DetectPlayerLeft_body_entered(body):
  LeftEntered = player
func _on_DetectPlayerForward_body_entered(body):
  ForwardEntered = player

area exited

func _on_DetectPlayerBack_body_exited(body):
  BackEntered = null
func _on_DetectPlayerRight_body_exited(body):
  RightEntered = null
func _on_DetectPlayerLeft_body_exited(body):
  LeftEntered = null
func _on_DetectPlayerForward_body_exited(body):
  ForwardEntered = null
in Engine by (298 points)

When the direction is negative, you do velocity.y -= speed, but when the direction is positive, you do velocity.y = speed. -= is just short hand for velocity.y = velocity.y - speed, meaning you keep substracting speed every frame, which makes your enemy accelerate. But velocity.y = speed is only setting the velocity to 50, meaning if it were moving, it would do so a lot slower than the other direction. My guess is that the enemy is moving, but you don't notice since the velocity is so low in the up or right directions. If I'm correct, then you also haven't tested the left direction, since you use -= there as well.

I guess that for forward and right, you meant to write velocity.y += speed and velocity.x += speed respectively.

Please log in or register to answer this question.

Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to webmaster@godotengine.org with your username.