S&box Wiki

Revision Difference

Bots#560472

<cat>Code.Player</cat>⤶ <title>Bots</title>⤶ ⤶ # What are bots?⤶ ⤶ Bots are fake clients that can be added to a game, and take a normal player slot. Their input and behaviour can be coded like most other things in C#.⤶ ⤶ # Default Bot⤶ ⤶ By default, the console command `bot_add` will add a bot that mimics another player's input. This command has some additional parameters you can use:⤶ ⤶ `bot_add <clientIndex> <yawOffset> <forceCrouch>`⤶ ⤶ **clientIndex** *(def: 1)* Which client to mimic. If set to 0, it will not mimic anything and remain idle. ⤶ **yawOffset** *(def: 180)* The bots yaw rotation relative to the target client. ⤶ **forceCrouch** *(def: 0)* Whether or not the bot is forced to crouch.⤶ ⤶ <note>Dedicated servers will fail to spawn default bots with this message:⤶ `SV: Cheat command 'bot_add' ignored. Set sv_cheats to 1 enable cheats.` *(sic!)*</note> ⤶ ⤶ #Custom Bots⤶ ⤶ To create a custom bot you need to first extend the `Bot` class, which has two important methods: `Tick` and `BuildInput`.⤶ ⤶ ## Example⤶ ⤶ It's worth noting that **the methods used below are only called server-side**, unlike ordinary clients whose input is built client-side and sent to the server.⤶ ⤶ ```csharp⤶ public class MyCustomBot : Bot⤶ {⤶ [ConCmd.Admin( "bot_custom", Help = "Spawn my custom bot." )]⤶ internal static void SpawnCustomBot()⤶ {⤶ Game.AssertServer();⤶ ⤶ // Create an instance of your custom bot.⤶ _ = new MyCustomBot();⤶ }⤶ ⤶ public override void BuildInput()⤶ {⤶ // Here we can choose / modify the bot's input each tick.⤶ // We'll make them constantly attack by holding down the PrimaryAttack button.⤶ Input.SetButton( InputButton.PrimaryAttack, true );⤶ // And here, we'll make the bot walk forward and turn in a wide circle.⤶ Input.AnalogMove = Vector3.Forward;⤶ Input.AnalogLook = new Angles( 0, 30 * Time.Delta, 0 );⤶ // Finally, we'll call BuildInput on the bot's client's pawn. ⤶ // Note that Entity.BuildInput is NOT automatically called for the pawns of⤶ // simulated clients that are driven by bots, so that's why we call it here.⤶ (Client.Pawn as Entity).BuildInput();⤶ }⤶ ⤶ public override void Tick()⤶ {⤶ // Here we can do something with the bot each tick.⤶ // Here we'll print our bot's name every tick.⤶ Log.Info( Client.Name );⤶ }⤶ }⤶ ```⤶ ⤶ In the above example, we are setting values of `Input` ourselves and then calling `BuildInput` on the pawn. This allows for the same code that handles real user input to also handle simulated inputs. ⤶ ⤶ ## Pawns⤶ ⤶ Each bot has a `Client` property referring to its underlying fake client. Every bot can have its own [Pawn](https://wiki.facepunch.com/sbox/Pawn) and otherwise do anything any other ordinary client could do.