• 2D
  • Rotate sprite and move to mouse click position. 2D

Hi,

With Python and pygame I used to do something like the following:

     if self.move_target and self.position != self.move_target:
            # find angle
            angle = math.atan2(self.move_target[1] - self.position[1], self.move_target[0] - self.position[0])
            turn_angle = -angle * 180 / math.pi
            self.turn_ship(turn_angle-90)

            # calculate correct velocity for x and y
            vel_x = int(round(self.current_speed * math.cos(angle)))
            vel_y = int(round(self.current_speed * math.sin(angle)))
            distance_x = self.move_target[0] - self.position[0]
            distance_y = self.move_target[0] - self.position[0]
            if abs(distance_x) < abs(vel_x) and abs(distance_y) < abs(vel_y):
                vel_x = distance_x
                vel_y = distance_y

            # change ship position, move sprite by (vel_x, vel_y)
            self.set_new_position(vel_x, vel_y)

Of course, it has some bugs, but I can't reproduce the same algorithm with Godot, sometimes it moves chaotically, probably because of bad math. On the other hand, I found, that it should be much easier with Godot, something like the following:

    func set_move_target(target):
    	target_pos = target
    
    func move_to_target(delta):
           rotation = -(target_pos.angle() * rotation_speed * delta)
           velocity = Vector2(speed, 0).rotated(rotation)
           return move_and_slide(velocity)	
    
    func _process(delta):
    	if Input.is_mouse_button_pressed(BUTTON_LEFT):
    		set_move_target(get_local_mouse_position())
    	
    	if target_pos:
    		move_to_target(delta)

But it moves even worse! It turns and moves into some random directions! What's wrong with my calculations and how to make it move correctly?

I've made some changes:

func set_move_target(target):
	target_pos = target
	angle_to_target = target_pos.angle()
	

func move_to_target(delta):
	velocity = Vector2(speed, 0).rotated(angle_to_target)
	return move_and_slide(velocity)	

In this case, moving my object is absolutely correct! But, it doesn't rotate to target position. And if I set property rotation everything breaks again. What's going on? How to perform correct rotation and moving to target position?

I can see where you would want to convert your existing code, but gdquest did a tutorial on steering behavior. Might help.

@fire7side Fantastic tutorial, thank you!