WebXRInterface Class |
WebXR is an open standard that allows creating VR and AR applications that run in the web browser.
As such, this interface is only available when running in an HTML5 export.
WebXR supports a wide range of devices, from the very capable (like Valve Index, HTC Vive, Oculus Rift and Quest) down to the much less capable (like Google Cardboard, Oculus Go, GearVR, or plain smartphones).
Since WebXR is based on Javascript, it makes extensive use of callbacks, which means that WebXRInterface is forced to use signals, where other AR/VR interfaces would instead use functions that return a result immediately. This makes WebXRInterface quite a bit more complicated to intialize than other AR/VR interfaces.
Here's the minimum code required to start an immersive VR session:
extends Spatial var webxr_interface var vr_supported = false func _ready(): # We assume this node has a button as a child. # This button is for the user to consent to entering immersive VR mode. $Button.connect("pressed", self, "_on_Button_pressed") webxr_interface = ARVRServer.find_interface("WebXR") if webxr_interface: # WebXR uses a lot of asynchronous callbacks, so we connect to various # signals in order to receive them. webxr_interface.connect("session_supported", self, "_webxr_session_supported") webxr_interface.connect("session_started", self, "_webxr_session_started") webxr_interface.connect("session_ended", self, "_webxr_session_ended") webxr_interface.connect("session_failed", self, "_webxr_session_failed") # This returns immediately - our _webxr_session_supported() method # (which we connected to the "session_supported" signal above) will # be called sometime later to let us know if it's supported or not. webxr_interface.is_session_supported("immersive-vr") func _webxr_session_supported(session_mode, supported): if session_mode == 'immersive-vr': vr_supported = supported func _on_Button_pressed(): if not vr_supported: OS.alert("Your browser doesn't support VR") return # We want an immersive VR session, as opposed to AR ('immersive-ar') or a # simple 3DoF viewer ('viewer'). webxr_interface.session_mode = 'immersive-vr' # 'bounded-floor' is room scale, 'local-floor' is a standing or sitting # experience (it puts you 1.6m above the ground if you have 3DoF headset), # whereas as 'local' puts you down at the ARVROrigin. # This list means it'll first try to request 'bounded-floor', then # fallback on 'local-floor' and ultimately 'local', if nothing else is # supported. webxr_interface.requested_reference_space_types = 'bounded-floor, local-floor, local' # In order to use 'local-floor' or 'bounded-floor' we must also # mark the features as required or optional. webxr_interface.required_features = 'local-floor' webxr_interface.optional_features = 'bounded-floor' # This will return false if we're unable to even request the session, # however, it can still fail asynchronously later in the process, so we # only know if it's really succeeded or failed when our # _webxr_session_started() or _webxr_session_failed() methods are called. if not webxr_interface.initialize(): OS.alert("Failed to initialize") return func _webxr_session_started(): $Button.visible = false # This tells Godot to start rendering to the headset. get_viewport().arvr = true # This will be the reference space type you ultimately got, out of the # types that you requested above. This is useful if you want the game to # work a little differently in 'bounded-floor' versus 'local-floor'. print ("Reference space type: " + webxr_interface.reference_space_type) func _webxr_session_ended(): $Button.visible = true # If the user exits immersive mode, then we tell Godot to render to the web # page again. get_viewport().arvr = false func _webxr_session_failed(message): OS.alert("Failed to initialize: " + message)
There are several ways to handle "controller" input:
- Using ARVRController nodes and their ARVRController.button_pressed and ARVRController.button_release signals. This is how controllers are typically handled in AR/VR apps in Godot, however, this will only work with advanced VR controllers like the Oculus Touch or Index controllers, for example. The buttons codes are defined by Section 3.3 of the WebXR Gamepads Module.
- Using _UnhandledInput(InputEvent) and InputEventJoypadButton or InputEventJoypadMotion. This works the same as normal joypads, except the Device starts at 100, so the left controller is 100 and the right controller is 101, and the button codes are also defined by Section 3.3 of the WebXR Gamepads Module.
- Using the select, squeeze and related signals. This method will work for both advanced VR controllers, and non-traditional "controllers" like a tap on the screen, a spoken voice command or a button press on the device itself. The controller_id passed to these signals is the same id as used in ControllerId.
You can use one or all of these methods to allow your game or app to support a wider or narrower set of devices and input methods, or to allow more advanced interations with more advanced devices.
Namespace: Godot
public abstract class WebXRInterface : ARVRInterface
The WebXRInterface type exposes the following members.
Name | Description | |
---|---|---|
![]() | ArIsAnchorDetectionEnabled | On an AR interface, true if anchor detection is enabled. |
![]() | BoundsGeometry | The vertices of a polygon which defines the boundaries of the user's play area. This will only be available if ReferenceSpaceType is "bounded-floor" and only on certain browsers and devices that support it. The reference_space_reset signal may indicate when this changes. |
![]() | DynamicObject |
Gets a new DynamicGodotObject associated with this instance.
(Inherited from Object.) |
![]() | InterfaceIsInitialized | true if this interface been initialized. |
![]() | InterfaceIsPrimary | true if this is the primary interface. |
![]() | NativeInstance | (Inherited from Object.) |
![]() | OptionalFeatures | A comma-seperated list of optional features used by Initialize when setting up the WebXR session. If a user's browser or device doesn't support one of the given features, initialization will continue, but you won't be able to use the requested feature. This doesn't have any effect on the interface when already initialized. Possible values come from WebXR's XRReferenceSpaceType. If you want to use a particular reference space type, it must be listed in either RequiredFeatures or OptionalFeatures. |
![]() | ReferenceSpaceType | The reference space type (from the list of requested types set in the RequestedReferenceSpaceTypes property), that was ultimately used by Initialize when setting up the WebXR session. Possible values come from WebXR's XRReferenceSpaceType. If you want to use a particular reference space type, it must be listed in either RequiredFeatures or OptionalFeatures. |
![]() | RequestedReferenceSpaceTypes | A comma-seperated list of reference space types used by Initialize when setting up the WebXR session. The reference space types are requested in order, and the first on supported by the users device or browser will be used. The ReferenceSpaceType property contains the reference space type that was ultimately used. This doesn't have any effect on the interface when already initialized. Possible values come from WebXR's XRReferenceSpaceType. If you want to use a particular reference space type, it must be listed in either RequiredFeatures or OptionalFeatures. |
![]() | RequiredFeatures | A comma-seperated list of required features used by Initialize when setting up the WebXR session. If a user's browser or device doesn't support one of the given features, initialization will fail and session_failed will be emitted. This doesn't have any effect on the interface when already initialized. Possible values come from WebXR's XRReferenceSpaceType. If you want to use a particular reference space type, it must be listed in either RequiredFeatures or OptionalFeatures. |
![]() | SessionMode | The session mode used by Initialize when setting up the WebXR session. This doesn't have any effect on the interface when already initialized. Possible values come from WebXR's XRSessionMode, including: "immersive-vr", "immersive-ar", and "inline". |
![]() | VisibilityState | Indicates if the WebXR session's imagery is visible to the user. Possible values come from WebXR's XRVisibilityState, including "hidden", "visible", and "visible-blurred". |
Name | Description | |
---|---|---|
![]() | _Get | Virtual method which can be overridden to customize the return value of Get(String). Returns the given property. Returns null if the property does not exist. |
![]() | _GetPropertyList | Virtual method which can be overridden to customize the return value of GetPropertyList. Returns the object's property list as an Array of dictionaries. Each property's Dictionary must contain at least name: String and type: int (see VariantType) entries. Optionally, it can also include hint: int (see PropertyHint), hint_string: String, and usage: int (see PropertyUsageFlags). |
![]() | _Notification | Called whenever the object receives a notification, which is identified in what by a constant. The base Object has two constants and , but subclasses such as Node define a lot more notifications which are also received by this method. |
![]() | _Set | Virtual method which can be overridden to customize the return value of Set(String, Object). Sets a property. Returns true if the property exists. |
![]() | AddUserSignal | Adds a user-defined signal. Arguments are optional, but can be added as an Array of dictionaries, each containing name: String and type: int (see VariantType) entries. |
![]() | Call | Calls the method on the object and returns the result. This method supports a variable number of arguments, so parameters are passed as a comma separated list. Example: call("set", "position", Vector2(42.0, 0.0)) Note: In C#, the method name must be specified as snake_case if it is defined by a built-in Godot node. This doesn't apply to user-defined methods where you should use the same convention as in the C# source (typically PascalCase). |
![]() | CallDeferred | Calls the method on the object during idle time. This method supports a variable number of arguments, so parameters are passed as a comma separated list. Example: call_deferred("set", "position", Vector2(42.0, 0.0)) Note: In C#, the method name must be specified as snake_case if it is defined by a built-in Godot node. This doesn't apply to user-defined methods where you should use the same convention as in the C# source (typically PascalCase). |
![]() | Callv | Calls the method on the object and returns the result. Contrarily to Call(String, Object), this method does not support a variable number of arguments but expects all parameters to be via a single Array. callv("set", [ "position", Vector2(42.0, 0.0) ]) |
![]() | CanTranslateMessages | Returns true if the object can translate strings. See SetMessageTranslation(Boolean) and Tr(String). |
![]() | Connect | Connects a signal to a method on a target object. Pass optional binds to the call as an Array of parameters. These parameters will be passed to the method after any parameter used in the call to EmitSignal(String, Object). Use flags to set deferred or one-shot connections. See ObjectConnectFlags constants. A signal can only be connected once to a method. It will throw an error if already connected, unless the signal was connected with . To avoid this, first, use IsConnected(String, Object, String) to check for existing connections. If the target is destroyed in the game's lifecycle, the connection will be lost. Examples: connect("pressed", self, "_on_Button_pressed") # BaseButton signal connect("text_entered", self, "_on_LineEdit_text_entered") # LineEdit signal connect("hit", self, "_on_Player_hit", [ weapon_type, damage ]) # User-defined signal An example of the relationship between binds passed to Connect(String, Object, String, Array, UInt32) and parameters used when calling EmitSignal(String, Object): connect("hit", self, "_on_Player_hit", [ weapon_type, damage ]) # weapon_type and damage are passed last emit_signal("hit", "Dark lord", 5) # "Dark lord" and 5 are passed first func _on_Player_hit(hit_by, level, weapon_type, damage): print("Hit by %s (lvl %d) with weapon %s for %d damage" % [hit_by, level, weapon_type, damage]) |
![]() | Disconnect | Disconnects a signal from a method on the given target. If you try to disconnect a connection that does not exist, the method will throw an error. Use IsConnected(String, Object, String) to ensure that the connection exists. |
![]() | Dispose | (Inherited from Object.) |
![]() | Dispose(Boolean) | (Inherited from Object.) |
![]() | EmitSignal | Emits the given signal. The signal must exist, so it should be a built-in signal of this class or one of its parent classes, or a user-defined signal. This method supports a variable number of arguments, so parameters are passed as a comma separated list. Example: emit_signal("hit", weapon_type, damage) emit_signal("game_over") |
![]() | Equals | (Inherited from Object.) |
![]() | Finalize | (Inherited from Object.) |
![]() | Free | Deletes the object from memory immediately. For Nodes, you may want to use QueueFree to queue the node for safe deletion at the end of the current frame. Important: If you have a variable pointing to an object, it will not be assigned to null once the object is freed. Instead, it will point to a previously freed instance and you should validate it with @GDScript.is_instance_valid before attempting to call its methods or access its properties. |
![]() | Get | Returns the Variant value of the given property. If the property doesn't exist, this will return null. Note: In C#, the property name must be specified as snake_case if it is defined by a built-in Godot node. This doesn't apply to user-defined properties where you should use the same convention as in the C# source (typically PascalCase). |
![]() | GetAnchorDetectionIsEnabled | Obsolete. (Inherited from ARVRInterface.) |
![]() | GetBoundsGeometry | Obsolete. |
![]() | GetCameraFeedId | If this is an AR interface that requires displaying a camera feed as the background, this method returns the feed ID in the CameraServer for this interface. |
![]() | GetCapabilities | Returns a combination of ARVRInterfaceCapabilities flags providing information about the capabilities of this interface. |
![]() | GetClass | Returns the object's class as a String. |
![]() | GetController | Gets an ARVRPositionalTracker for the given controller_id. In the context of WebXR, a "controller" can be an advanced VR controller like the Oculus Touch or Index controllers, or even a tap on the screen, a spoken voice command or a button press on the device itself. When a non-traditional controller is used, interpret the position and orientation of the ARVRPositionalTracker as a ray pointing at the object the user wishes to interact with. Use this method to get information about the controller that triggered one of these signals: - selectstart - select - selectend - squeezestart - squeeze - squeezestart |
![]() | GetHashCode | (Inherited from Object.) |
![]() | GetIncomingConnections | Returns an Array of dictionaries with information about signals that are connected to the object. Each Dictionary contains three String entries: - source is a reference to the signal emitter. - signal_name is the name of the connected signal. - method_name is the name of the method to which the signal is connected. |
![]() | GetIndexed | Gets the object's property indexed by the given NodePath. The node path should be relative to the current object and can use the colon character (:) to access nested properties. Examples: "position:x" or "material:next_pass:blend_mode". |
![]() | GetInstanceId | Returns the object's unique instance ID. This ID can be saved in EncodedObjectAsID, and can be used to retrieve the object instance with @GDScript.instance_from_id. |
![]() | GetMeta | Returns the object's metadata entry for the given name. |
![]() | GetMetaList | Returns the object's metadata as a String. |
![]() | GetMethodList | Returns the object's methods and their signatures as an Array. |
![]() | GetName | Returns the name of this interface (OpenVR, OpenHMD, ARKit, etc). |
![]() | GetOptionalFeatures | Obsolete. |
![]() | GetPropertyList | Returns the object's property list as an Array of dictionaries. Each property's Dictionary contain at least name: String and type: int (see VariantType) entries. Optionally, it can also include hint: int (see PropertyHint), hint_string: String, and usage: int (see PropertyUsageFlags). |
![]() | GetReferenceSpaceType | Obsolete. |
![]() | GetRenderTargetsize | Returns the resolution at which we should render our intermediate results before things like lens distortion are applied by the VR platform. |
![]() | GetRequestedReferenceSpaceTypes | Obsolete. |
![]() | GetRequiredFeatures | Obsolete. |
![]() | GetScript | Returns the object's Script instance, or null if none is assigned. |
![]() | GetSessionMode | Obsolete. |
![]() | GetSignalConnectionList | Returns an Array of connections for the given signal. |
![]() | GetSignalList | Returns the list of signals as an Array of dictionaries. |
![]() | GetTrackingStatus | If supported, returns the status of our tracking. This will allow you to provide feedback to the user whether there are issues with positional tracking. |
![]() | GetType | (Inherited from Object.) |
![]() | GetVisibilityState | Obsolete. |
![]() | HasMeta | Returns true if a metadata entry is found with the given name. |
![]() | HasMethod | Returns true if the object contains the given method. |
![]() | HasSignal | Returns true if the given signal exists. |
![]() | HasUserSignal | Returns true if the given user-defined signal exists. Only signals added using AddUserSignal(String, Array) are taken into account. |
![]() | Initialize | Call this to initialize this interface. The first interface that is initialized is identified as the primary interface and it will be used for rendering output. After initializing the interface you want to use you then need to enable the AR/VR mode of a viewport and rendering should commence. Note: You must enable the AR/VR mode on the main viewport for any device that uses the main output of Godot, such as for mobile VR. If you do this for a platform that handles its own output (such as OpenVR) Godot will show just one eye without distortion on screen. Alternatively, you can add a separate viewport node to your scene and enable AR/VR on that viewport. It will be used to output to the HMD, leaving you free to do anything you like in the main window, such as using a separate camera as a spectator camera or rendering something completely different. While currently not used, you can activate additional interfaces. You may wish to do this if you want to track controllers from other platforms. However, at this point in time only one interface can render to an HMD. |
![]() | InitRef | Initializes the internal reference counter. Use this only if you really know what you are doing. Returns whether the initialization was successful. |
![]() | IsBlockingSignals | Returns true if signal emission blocking is enabled. |
![]() | IsClass | Returns true if the object inherits from the given class. |
![]() | IsConnected | Returns true if a connection exists for a given signal, target, and method. |
![]() | IsInitialized | Obsolete. (Inherited from ARVRInterface.) |
![]() | IsPrimary | Obsolete. (Inherited from ARVRInterface.) |
![]() | IsQueuedForDeletion | Returns true if the QueueFree method was called for the object. |
![]() | IsSessionSupported | Checks if the given session_mode is supported by the user's browser. Possible values come from WebXR's XRSessionMode, including: "immersive-vr", "immersive-ar", and "inline". This method returns nothing, instead it emits the session_supported signal with the result. |
![]() | IsStereo | Returns true if the current output of this interface is in stereo. |
![]() | MemberwiseClone | (Inherited from Object.) |
![]() | Notification | Send a given notification to the object, which will also trigger a call to the _Notification(Int32) method of all classes that the object inherits from. If reversed is true, _Notification(Int32) is called first on the object's own class, and then up to its successive parent classes. If reversed is false, _Notification(Int32) is called first on the highest ancestor (Object itself), and then down to its successive inheriting classes. |
![]() | PropertyListChangedNotify | Notify the editor that the property list has changed, so that editor plugins can take the new values into account. Does nothing on export builds. |
![]() | Reference_ | Increments the internal reference counter. Use this only if you really know what you are doing. Returns true if the increment was successful, false otherwise. |
![]() | RemoveMeta | Removes a given entry from the object's metadata. See also SetMeta(String, Object). |
![]() | Set | Assigns a new value to the given property. If the property does not exist, nothing will happen. Note: In C#, the property name must be specified as snake_case if it is defined by a built-in Godot node. This doesn't apply to user-defined properties where you should use the same convention as in the C# source (typically PascalCase). |
![]() | SetAnchorDetectionIsEnabled | Obsolete. (Inherited from ARVRInterface.) |
![]() | SetBlockSignals | If set to true, signal emission is blocked. |
![]() | SetDeferred | Assigns a new value to the given property, after the current frame's physics step. This is equivalent to calling Set(String, Object) via CallDeferred(String, Object), i.e. call_deferred("set", property, value). Note: In C#, the property name must be specified as snake_case if it is defined by a built-in Godot node. This doesn't apply to user-defined properties where you should use the same convention as in the C# source (typically PascalCase). |
![]() | SetIndexed | Assigns a new value to the property identified by the NodePath. The node path should be relative to the current object and can use the colon character (:) to access nested properties. Example: set_indexed("position", Vector2(42, 0)) set_indexed("position:y", -10) print(position) # (42, -10) |
![]() | SetIsInitialized | Obsolete. (Inherited from ARVRInterface.) |
![]() | SetIsPrimary | Obsolete. (Inherited from ARVRInterface.) |
![]() | SetMessageTranslation | Defines whether the object can translate strings (with calls to Tr(String)). Enabled by default. |
![]() | SetMeta | Adds, changes or removes a given entry in the object's metadata. Metadata are serialized and can take any Variant value. To remove a given entry from the object's metadata, use RemoveMeta(String). Metadata is also removed if its value is set to null. This means you can also use set_meta("name", null) to remove metadata for "name". |
![]() | SetOptionalFeatures | Obsolete. |
![]() | SetRequestedReferenceSpaceTypes | Obsolete. |
![]() | SetRequiredFeatures | Obsolete. |
![]() | SetScript | Assigns a script to the object. Each object can have a single script assigned to it, which are used to extend its functionality. If the object already had a script, the previous script instance will be freed and its variables and state will be lost. The new script's method will be called. |
![]() | SetSessionMode | Obsolete. |
![]() ![]() | ToSignal |
Returns a new SignalAwaiter awaiter configured to complete when the instance
source emits the signal specified by the signal parameter.
(Inherited from Object.) |
![]() | ToString | (Inherited from Object.) |
![]() | Tr | Translates a message using translation catalogs configured in the Project Settings. Only works if message translation is enabled (which it is by default), otherwise it returns the message unchanged. See SetMessageTranslation(Boolean). |
![]() | Uninitialize | Turns the interface off. |
![]() | Unreference | Decrements the internal reference counter. Use this only if you really know what you are doing. Returns true if the decrement was successful, false otherwise. |