Work in progress

The content of this page was not yet updated for Godot 4.2 and may be outdated. If you know how to improve this page or you can confirm that it's up to date, feel free to open a pull request.

Referência da classe shell HTML5

Os projetos exportados para a Web expõem a classe Engine() ao ambiente JavaScript, que permite um controle fino sobre o processo de partida do motor.

Este API é construído de uma maneira assíncrona e requer conhecimento básico sobre Promises.

Engine

A classe Engine fornece métodos para carregar e inicializar projetos exportados na Web. Para configurações de exportação padrão, isto já é parte da página HTML exportada. Para entender o uso prático da classe Engine, veja Personalizar página HTML para exportação Web.

Métodos Estáticos

Promise

load ( string basePath )

void

unload ( )

booleano

isWebGLAvailable ( [ number majorVersion=1 ] )

Métodos de Instância

Promise

init ( [ string basePath ] )

Promise

preloadFile ( string|ArrayBuffer file [, string path ] )

Promise

start ( EngineConfig override )

Promise

startGame ( EngineConfig override )

void

copyToFS ( string path, ArrayBuffer buffer )

void

requestQuit ( )

class Engine(initConfig)

Criar uma nova instância de Engine com a configuração dada.

Argumentos
  • initConfig (EngineConfig()) -- The initial config for this instance.

Métodos Estáticos

Engine.load(basePath)

Load the engine from the specified base path.

Argumentos
  • basePath (string()) -- Base path of the engine to load.

Retorna

A Promise that resolves once the engine is loaded.

Tipo de retorno

Promise

Engine.unload()

Unload the engine to free memory.

This method will be called automatically depending on the configuration. See unloadAfterInit.

Engine.isWebGLAvailable([majorVersion=1])

Check whether WebGL is available. Optionally, specify a particular version of WebGL to check for.

Argumentos
  • majorVersion (number()) -- The major WebGL version to check for.

Retorna

If the given major version of WebGL is available.

Tipo de retorno

booleano

Métodos de instância

Engine.prototype.init([basePath])

Initialize the engine instance. Optionally, pass the base path to the engine to load it, if it hasn't been loaded yet. See Engine.load().

Argumentos
  • basePath (string()) -- Base path of the engine to load.

Retorna

A Promise that resolves once the engine is loaded and initialized.

Tipo de retorno

Promise

Engine.prototype.preloadFile(file[, path])

Load a file so it is available in the instance's file system once it runs. Must be called before starting the instance.

If not provided, the path is derived from the URL of the loaded file.

Argumentos
  • file (string|ArrayBuffer()) --

    O arquivo a ser pré-carregado.

    Se for uma string, o arquivo será carregado a partir desse caminho.

    If an ArrayBuffer or a view on one, the buffer will used as the content of the file.

  • path (string()) -- Caminho pelo qual o arquivo estará acessível. Obrigatório, se arquivo não for uma string.

Retorna

A Promise that resolves once the file is loaded.

Tipo de retorno

Promise

Engine.prototype.start(override)

Inicie a instância da engine usando a configuração de substituição fornecida (se houver). startGame pode ser usado em casos típicos.

This will initialize the instance if it is not initialized. For manual initialization, see init. The engine must be loaded beforehand.

Fails if a canvas cannot be found on the page, or not specified in the configuration.

Argumentos
Retorna

Promise that resolves once the engine started.

Tipo de retorno

Promise

Engine.prototype.startGame(override)

Start the game instance using the given configuration override (if any).

This will initialize the instance if it is not initialized. For manual initialization, see init.

This will load the engine if it is not loaded, and preload the main pck.

This method expects the initial config (or the override) to have both the executable and mainPack properties set (normally done by the editor during export).

Argumentos
Retorna

Promise that resolves once the game started.

Tipo de retorno

Promise

Engine.prototype.copyToFS(path, buffer)

Create a file at the specified path with the passed as buffer in the instance's file system.

Argumentos
  • path (string()) -- O local onde o arquivo será criado.

  • buffer (ArrayBuffer()) -- O conteúdo do arquivo.

Engine.prototype.requestQuit()

Solicite que a instância atual seja encerrada.

This is akin the user pressing the close button in the window manager, and will have no effect if the engine has crashed, or is stuck in a loop.

Configuração da engine

An object used to configure the Engine instance based on godot export options, and to override those in custom HTML templates if needed.

Propriedades

tipo

name

booleano

unloadAfterInit

HTMLCanvasElement

canvas

string

executable

string

mainPack

string

locale

número

canvasResizePolicy

Matriz.<string>

args

função

onExecute

função

onExit

função

onProgress

função

onPrint

função

onPrintError

EngineConfig

The Engine configuration object. This is just a typedef, create it like a regular object, e.g.:

const MyConfig = { executable: 'godot', unloadAfterInit: false }

Descrições de propriedade

unloadAfterInit

Whether the unload the engine automatically after the instance is initialized.

tipo

booleano

Valor

true

canvas

The HTML DOM Canvas object to use.

By default, the first canvas element in the document will be used is none is specified.

tipo

HTMLCanvasElement

Valor

null

executable

The name of the WASM file without the extension. (Set by Godot Editor export process).

tipo

string

Valor

""

mainPack

An alternative name for the game pck to load. The executable name is used otherwise.

tipo

string

Valor

null

locale

Specify a language code to select the proper localization for the game.

O local de navegação será usado se nenhum for especificado. Veja a lista completa de locais suportados.

tipo

string

Valor

null

canvasResizePolicy

The canvas resize policy determines how the canvas should be resized by Godot.

0 means Godot won't do any resizing. This is useful if you want to control the canvas size from javascript code in your template.

1 means Godot will resize the canvas on start, and when changing window size via engine functions.

2 means Godot will adapt the canvas size to match the whole browser window.

tipo

número

Valor

2

args

Os argumentos a serem passados como argumentos de linha de comando na inicialização.

See command line tutorial.

Note: startGame will always add the --main-pack argument.

tipo

Matriz.<string>

Valor

[]

onExecute(path, args)

A callback function for handling Godot's OS.execute calls.

This is for example used in the Web Editor template to switch between Project Manager and editor, and for running the game.

Argumentos
  • path (string()) -- The path that Godot's wants executed.

  • args (Array.) -- The arguments of the "command" to execute.

onExit(status_code)

A callback function for being notified when the Godot instance quits.

Note: This function will not be called if the engine crashes or become unresponsive.

Argumentos
  • status_code (number()) -- The status code returned by Godot on exit.

onProgress(current, total)

A callback function for displaying download progress.

The function is called once per frame while downloading files, so the usage of requestAnimationFrame() is not necessary.

If the callback function receives a total amount of bytes as 0, this means that it is impossible to calculate. Possible reasons include:

  • Os arquivos são entregues com compressão fragmentada do lado do servidor

  • Os arquivos são entregues com compactação do lado do servidor no Chromium

  • Nem todos os downloads de arquivos foram iniciados ainda (geralmente em servidores sem multi-threading)

Argumentos
  • current (number()) -- The current amount of downloaded bytes so far.

  • total (number()) -- The total amount of bytes to be downloaded.

onPrint([...var_args])

A callback function for handling the standard output stream. This method should usually only be used in debug pages.

By default, console.log() is used.

Argumentos
  • var_args (*()) -- A variadic number of arguments to be printed.

onPrintError([...var_args])

A callback function for handling the standard error stream. This method should usually only be used in debug pages.

By default, console.error() is used.

Argumentos
  • var_args (*()) -- A variadic number of arguments to be printed as errors.