How to change a players game mode when crossing a threshold [duplicate]

Solution 1:

This answer covers the main question and Bonus #1, but not Bonus #2.

Target selectors can be used to select a player in a cuboid area.

I'd first set up a dummy objective, which will store whether or not a player is in the area:

/scoreboard objectives add inCreativeArea dummy

As an overview, you then want to, in this order on a clock:

  1. Set everyone who is in this specific area's inCreativeArea score to 3
  2. Reduce everyone's inCreativeArea score by 1
  3. Give creative mode to anyone with an inCreativeArea score of 2, survival mode for anyone with an inCreativeArea score of below that
  4. Teleport anyone with an inCreativeArea score of 1 to the ground

1

The actual command for this part should look something like:

/scoreboard players set @a[X,Y,Z,dx=DX,dy=DY,dz=DZ] inCreativeArea 3

Replace the capital X, Y and Z with the coordinates of the most negative corner of the cuboid creative area, and the DX, DY, DZ with the length, height and width of the area.

This sets anyone who is in the creative area's score to 3.

2

/scoreboard players remove @a[score_inCreativeArea_min=1] inCreativeArea 1

This reduces everyone's inCreativeArea score by 1. People who are in the area will now have a score of 2, people who just left the area a score of 1, and others a score of 0.

3

/gamemode 1 @a[score_inCreativeArea_min=2,m=0]
/gamemode 0 @a[score_inCreativeArea=0,m=1]

These set the gamemodes appropriately. The m argument prevents it updating people who are already in that gamemode, which would work but spam their screen endlessly with the "Your game mode has been updated" message.

4

Finally, the easiest way to teleport players who have just left to the ground is a relative spreadplayers command which always chooses a location on a solid block:

/execute @a[score_inCreativeArea_min=1,score_inCreativeArea=1] ~ ~ ~ spreadplayers ~ ~ 0 1 false @p