Movement formula using rolls and str (?)

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

Hello, I’m making an AI move to preset locations based on two different rolls.
One roll for if it moves in the first place: var timermove = (["1", "2", "3", "4", "5", "6"])
And the other roll for if it moves to the location in front of it or the location behind it:

var move = (["back", "forward"])

The roll to see IF it moves is on a timer that rolls every 4 seconds, and the locations are position 2D nodes called Location1 Location2 Location3 Location4 etc. up to 6.

Here’s the timeout function:

var move = (["back", "forward"])
var direction = move[randi() % move.size()]
var roll = timermove[randi() % timermove.size()]
if roll == "1":
	if direction[1]:
		$Enemy.position = get_node("Location" + str(+1))
	if direction[0]:
		$Enemy.position = get_node("Location" + str(-1))

This is just a rough draft since I’m not sure how to go about this. I named the location where they start Location0 and want to also be able to have them only have the option to move to Location1 for the first movement, and then after that have them be unable to return to Location0 so they’ll bounce around between Location1 - Location6.

Can anyone point me in the right direction or let me know if something is blatantly wrong?

:bust_in_silhouette: Reply From: jgodfrey

I think the general idea here is fine, but it’s more complex than necessary. Here are a few changes worth considering:

  • Change thetimermove array to contain integer values instead of strings (1-6)
  • Change the move array to contain [-1, 1] instead of the strings you now have.
  • Continue to select the direction and roll like you are now, though you’ll now get 2 integer values back.
  • Store references to the Position2D nodes in an array, where the index relates to its position.
  • Create an integer variable to track your current “position” on the board (1-6)

Now, when you “roll”, take the 2 ints you get back and multiply them together. You’ll get negative values for “backwards” moves and positive values for “forward” moves.

Add the new value to your current “position” variable to get the new position, and use that value to access the position array to get the referene to the correct Position2D node.

If the new position exceeds your last position, set it to the last position. If it’s less than 1, set it to 1.

That should be much easier to manage than the strings you have now.

You’ll need to account for the fact that the array will start with element 0 rather than 1, but you could use that to your advantage and assign element 0 to be your starting square. That way, array indices 1-6 would directly align with your expected positions.

Then, just season to taste… :slight_smile: