Why doesn't look_at() work when only used once?

Godot Version

Godot v4.2.2.stable - Windows 10.0.22631

Question

Hi! I’m very new to Godot, so I hopped straight in to the “Create your first 2D Game” tutorial on the official documentation, created the “Dodge the Creeps” game, and then decided to add some modifications to it to make it my own.

Basically, my idea was to make three separate AI for the mob, who uses three different pairs of animations. Specifically, for my “Fly” mob, I wanted it to bounce off the edge of the screen once and go all the way back before despawning.

Here is the code I used:

func _on_edge_detector_screen_exited():
	if mob_type == "fly" and not detecting_edge:
		detecting_edge = true # Only allows for one bounce
		linear_velocity = -linear_velocity # Flips movement direction
		look_at(position + linear_velocity)

This function is hooked up to a VisibleOnscreenNotifier2D that’s on the edge of the mob. The mob successfully goes backwards, however, the look_at statement, for some reason, didn’t update the rotation at all.

Unless, I put inside it inside a physics_process function:

func _physics_process(delta):
	if mob_type == "swim":
		# Irrelevant code here
	elif mob_type == "fly":
		look_at(position + linear_velocity)

Then, it suddenly starts working perfectly. Can someone explain to me the reason for this? Is it just some physics delay, and if it is, is there a way to do this better than just repeatedly calling on the look_at() function within physics_process?

RigidBodies have physics control their rotation, directly editing rotation has to happen during physics or else the physics simulation will override your changes.

Maybe if you set “lock_rotation” in the mob’s properties, changing rotation will stick outside of physics? Sometimes deferring a change works too, set_deferred("rotation", rotation-PI)

1 Like

Thanks! Setting lock_rotation on did work, but strangely, once I turned it off again, it still kept working?

You probably don’t ever have to turn it off :slight_smile:

1 Like

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.