Skip to content

Scripting

fed edited this page Sep 27, 2021 · 15 revisions

Introduction

This is the documentation for H2-Mod's scripting API.
This documentation is complementary to IW6x' scripting API so be sure to check out their wiki first if you are not familiar with it.

Example script

Because this is singleplayer there are no notifies like "connected" or "spawned_player" like there are in multiplayer, instead all scripts are loaded once the player has spawned which is accessible through the global player variable:

-- Script loaded and player spawned

-- Let the game's GSC scripts initialize first
game:ontimeout(function()
    player:setorigin(vector:new(10000, 10000, 10000)
end, 0)

Note that the player spawns as soon as the map loads but not after the loading screen cinematic ends so your script will start even if you aren’t yet "in-game".
To fix this wait for another server frame before running your code:

game:ontimeout(function()
    game:ontimeout(function()
        player:setorigin(vector:new(10000, 10000, 10000)
    end, 0)
end, 0)

-- This should also work fine:

game:ontimeout(function()
    player:setorigin(vector:new(10000, 10000, 10000)
end, 100)

Extra features

H2-Mod's scripting API includes features that are either not documented or don't exist on IW6x

Entity damage callbacks

You can 'hook' the game's entity damage function in order to modify the damage using the game:onentitydamage function:

-- When you (the player) get damaged the entity that actually gets damage 
-- first isn't the global `player` entity but the entity of number `1` and classname `scriptable`

local scriptableplayer = game:getentbynum(1)

game:onentitydamage(function(_self, inflictor, attacker, damage, mod, weapon, dir, hitloc)
    if (_self == scriptableplayer) then
        -- If the victim is you (the player) set the damage to 0
        return 0
    end
end)

Arrays

Arrays are supported and can be accessed similarly to GSC:

local ents = game:getentarray()

for i = 1, #ents do
    print(ents[i])
end

Structs

GSC structs are also supported similarly as the arrays. The difference is that struct fields are accessed not using the field name but using the field name's string id which is created at compile time, so if you wanted to access a specific field of a struct you would first need to find that its id by looking at the game's decompiled gsc scripts which you can find here.
Example:

In maps/favela_escape.gsc the first function we find is

To get an entity's struct you can use the getstruct method or the struct field:

player.struct.inGracePeriod = 10000

Note: you cannot create new struct fields but only modify or read existing ones, same thing for arrays

Clone this wiki locally