Why doesn't my integrate_forces process detect if a variable is true?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By SuperSopwith
func _integrate_forces(state):
if selected == true:
    currentposition = get_position()
    angletomouse = currentposition.angle_to(get_global_mouse_position())
    directionfm = Vector2(cos(angletomouse), sin(angletomouse))
    add_central_force(directionfm * movespeed)
    selected = false

Basically when you click in an on a Rigidbody2D selected is set to true. However, for some reason, the integrate_forces process is not detecting this, so isn’t running. Does anyone have any idea why this could be?

2 things…

  • Please format the above code to make it more readable (edit your post, select the code, press the “{ }” button in the forum editor’s toolbar).
  • Post the code that’s setting selected = true

jgodfrey | 2020-09-01 20:47

Also, if you ever get into that elseblock, selected is already false, so setting it false doesn’t seem to be doing anything…

jgodfrey | 2020-09-01 20:50

Sorry about that, it should be readable now.
Here is the code that sets selected to true:

func _on_Area2D_input_event(viewport, event, shape_idx):
if event is InputEventMouseButton:
	if event.is_pressed():
		selected = true		
		selected = false

SuperSopwith | 2020-09-01 21:20

:bust_in_silhouette: Reply From: jgodfrey

And, those two snippets are from the same script I assume, right?

I don’t see anything obvious, so you might try a few things to help track this down:

  • Are you sure that the selected = true code ever executes? I’d add a print statement inside that if event.is_pressed(): block to make sure you’re getting there.
  • What happens if you print selected at the top of your _integrated_forces() function?
  • Does the code in _integrate_forces() get executed if you remove the if clause?

With those answers, it should be fairly easy to determine where the problem is.

I sort of assume that selected is never getting set to true…

Oh, wait. I think that input event handler will only fire in the frame where the button is pressed, and won’t fire again until the button is pressed again. Just print out the value of selected at the end of that handler and I think you’ll find that it’s only true in the single frame where the button is clicked. I bet that’s your problem. If that’s the case, your _integrate_forces() function will only function in that single frame too…

Thanks!! This was really useful! I really appreciate it!

SuperSopwith | 2020-09-02 13:21