Enemy Sprite not Flipping in V

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Spafnar

I have a RigidBody2D Node called fireball that will be spawning from bottom of the stage and shooting up. It has a gravity scale of 1.7 and I planned on it falling back down and flipping the sprite with it. The code so far is very simple, however, running early tests in the fireball scene doesn’t have it flipping the fireball to show it flying downwards. Here is the code.

extends RigidBody2D

export var minspeed = 400
export var maxspeed = 550

func process(delta):
var velocity = Vector2.ZERO
$Sprite.flip_v = velocity.y < 0

Its a fairly simple code but it doesn’t seem to be working, can anyone help me. In the main scene, I have the spawn point beneath the player viewrect and they shoot up and then the gravity will obviously have them go back down to where they were. Does the fact that the gravity is what’s moving it and not its own speed have something to do with it?

:bust_in_silhouette: Reply From: djmick

You are correct, the rigidbody is using gravity to move it and not its own speed, so velocity is always (0, 0), so the sprite never flips. In addition, your minspeed and maxspeed aren’t doing anything. I wrote this quick code it’s more complicated than yours, but it should work. Tell me if anything messed up though and I can fix it:

extends RigidBody2D

var direction = "up"
var last_pos = global_position.y

func _process(delta):
	if last_pos < global_position.y:
		last_pos = global_position.y
		direction = "down"
	elif last_pos > global_position.y:
		last_pos = global_position.y
		direction = "down"
	match direction:
			$Sprite.flip_v = false
			$Sprite.flip_v = true

I will try it, but I should mention the min and max speed are used elsewhere in the main function. In the Fireball spawn timer, the last bit of code is:

var velocity = Vector2(rand_range(ball.min_speed, ball.max_speed), 0)
ball.linear_velocity = velocity.rotated(direction)

which is how it shoots up in the first place.

Spafnar | 2021-02-04 17:12

Awesome, yes, it does seem to be working; just so I know how it works; this code is instead looking at the position of the fireball instead of the movement speed to determine if its flipped?

Spafnar | 2021-02-04 17:19

I’m glad it worked! I set a variable for the position last frame and compare it to the current position. If it’s less that means that position is moving down, and vice versa, so I set the direction variable based on if it’s currently moving up or down. The match statement just handles the sprite part.

djmick | 2021-02-04 17:21