MPmostafa it is usually easier to make your movements into functions and then use logic to determine what happens when, but I am guessing you are looking for something simpler.
I can see one problem for sure. You can't use move_toward
on a sprite. You can use basic movement code but you need more than what you have above. Also, your movement needs to be in physics_process
, not process
. You also need a base velocity (Vector2.ZERO
) and a speed variable so your code knows how fast to move each object. Use process
for values or things to update each frame. Physics only updates each frame so if you try to plug in physics values before a scene is ready, it can cause problems. So update it in the code, not the header.
I am bored and limiting myself to detailing one room a day in my current project so I gave you some working code.
extends Node2D
### i made a separate node to handle this and it works because it has access to data from both nodes, no globals, with both sprites as children.
onready var comp = get_node("Blackfish")
var comp_velocity = Vector2.ZERO ### this is your base vector, gives your movement base x/y values
var pos ## update this in process so you can constantly check position, hence "chasing"
var _compspeed = 500 ## this value is your speed, you can also export it so you can change values in editor
onready var player = get_node("Yellowfish")
var player_velocity = Vector2.ZERO
var pos2
func _ready():
_pos_update() ## update values at ready
func _pos_update(): ### this function catches x/y values and updates them
pos = comp.global_position
pos2 = player.global_position
func _process(_delta):
_pos_update() ## run the pos check every frame
func _moving(): ## here, we check x and y and change position based on data
if pos2.x > pos.x:
comp.position.x+=1
if pos2.x < pos.x:
comp.position.x-=1
if pos2.y > pos.y:
comp.position.y+=1
if pos2.y < pos.y:
comp.position.y-=1
func _physics_process(_delta): ## and HERE's your movement, working
_moving()
comp_velocity = comp_velocity.normalized() * _compspeed
I only did this with enemy moving, it should be enough for you to figure out player movement. I recommend the tutorial on 2D movement in the documentation.
2D Movement Basics - Official GODOT Docs 3.5