Search Results for

    Show / Hide Table of Contents

    Add a charge bonus to the primary weapon

    中文 | English

    Run this command at the repository root to replay the examples through the local Unity MCP.

    python Docs/Manual/manual/tools/tutorials.py run lua-api2-charged-shot
    
    Click to expand MCP actionsClick to collapse MCP actions

    Prepare the teaching sample. The recipe provides ${variables}.

    {
      "variables": {
        "script": "${fixture}/ChargedShot.lua",
        "prefab": "${fixture}/Tutorial_ChargedShot.prefab"
      },
      "calls": [
        {
          "tool": "invoke",
          "arguments": {
            "path": "static:UnityEditor.AssetDatabase/CreateFolder",
            "args": [
              "${fixtureParent}",
              "${folder}"
            ]
          },
          "expect": {
            "contains": "(String)"
          }
        }
      ]
    }
    

    1. Import the script and attach it to a vehicle

    Create ChargedShot.lua in your Lua source folder and copy in the script below. Follow Lua Hello World to import it into Unity, then add the asset to the vehicle-level Lua behaviours in VehicleTextData. For a test prefab, you can also attach it with LuaBehaviorMono on an object in the vehicle hierarchy.

    Keep chargeTime = 4 seconds and maxBonus = 0.5 for the first test. The example uses weapon index 0. To pick another weapon, check the available count with WeaponAPI.GetWeaponCount and change the index. The script disables periodic updates if the weapon is missing or charge time is zero or negative.

    Use BuffAPI.CreateValueBuff to attach one mutable buff to the weapon's DamageBuffedCoff. Passing false for the second argument makes it additive. A value of 0.5 adds 50%. Passing true gives a multiplier that stacks multiplicatively. Keep one object and use SetValue to update it. An unchanged value leaves it as-is. On destruction, remove it with RemoveBuff.

    Behavior()
    Property = {
        maxBonus = { type = "number", value = 0.5 },
        chargeTime = { type = "number", value = 4 },
    }
    
    local ChargedShot = class("ChargedShot")
    
    function ChargedShot:OnVehicleReady(vehicle)
        local weapon = WeaponAPI.GetWeapon(vehicle, 0)
        if weapon == nil or self.chargeTime <= 0 then
            self.script:SetUpdateEnabled(false)
            return
        end
        self.weapon = weapon
        self.damage = weapon.DamageBuffedCoff
        self.charge = 0
        self.buff = BuffAPI.CreateValueBuff("Charged Shot", false, 0)
        self.damage:AddBuff(self.buff)
        WeaponAPI.OnFired(self.script, weapon, function()
            self.charge = 0
            self.buff:SetValue(0)
        end)
        self.script:SetUpdateInterval(0.1)
    end
    
    function ChargedShot:OnUpdated(dt)
        if self.buff == nil or not WeaponAPI.IsReloaded(self.weapon) then
            return
        end
        self.charge = math.min(self.charge + dt / self.chargeTime, 1)
        self.buff:SetValue(self.charge * self.maxBonus)
    end
    
    function ChargedShot:OnDestroyed()
        if self.buff ~= nil then
            self.damage:RemoveBuff(self.buff)
            self.buff = nil
        end
    end
    
    return ChargedShot
    
    Click to expand MCP actionsClick to collapse MCP actions
    [
      {
        "tool": "invoke",
        "arguments": {
          "path": "static:System.IO.File/Copy",
          "args": [
            "../../Docs/Manual/tutorials/lua-api2-charged-shot/example.lua",
            "${script}"
          ]
        },
        "expect": {
          "contains": "OK:"
        }
      },
      {
        "tool": "invoke",
        "arguments": {
          "path": "static:UnityEditor.AssetDatabase/ImportAsset",
          "args": [
            "${script}",
            "ForceSynchronousImport"
          ]
        },
        "expect": {
          "contains": "OK:"
        }
      },
      {
        "tool": "prefab_edit",
        "arguments": {
          "json": {
            "path": "${prefab}",
            "mode": "create",
            "component": "ShanghaiWindy.Core.Lua.LuaBehaviorMono",
            "children": [],
            "references": [
              {
                "property": "luaBehavior",
                "asset": "${script}",
                "type": "ShanghaiWindy.Core.Lua.LuaBehaviorScript"
              }
            ],
            "values": {
              "instanceLuaProperty": {
                "numberProperties": [
                  {
                    "variableName": "maxBonus",
                    "value": 0.5
                  },
                  {
                    "variableName": "chargeTime",
                    "value": 4
                  }
                ]
              }
            }
          }
        },
        "expect": {
          "equals": {
            "ok": true
          }
        }
      },
      {
        "tool": "inspect",
        "arguments": {
          "path": "asset:${prefab}/LuaBehaviorMono/luaBehavior/name"
        },
        "expect": {
          "contains": "(String) ChargedShot"
        }
      }
    ]
    

    2. Test reload, charge, and fire in order

    1. Let the weapon finish reloading. The script skips charging during reload.
    2. Wait about two seconds and fire once. Reload, wait more than four seconds, and fire again. Log self.charge temporarily to check that it grows by dt / chargeTime and stops at 1. The update interval is 0.1 seconds. The script accumulates the actual dt it receives.
    3. Check that OnFired clears both the charge and the buff amount. After removing the behaviour, check that its buff was removed from the weapon. To compare damage in game, keep the ammo, target, and hit location consistent.

    The replay uses xLua test doubles to check the reload gate, charge limit, firing reset, and cleanup.

    Click to expand MCP actionsClick to collapse MCP actions
    [
      {
        "tool": "invoke",
        "arguments": {
          "path": "static:ShanghaiWindy.Core.AssetBundleManager/LuaEnv/DoString",
          "args": [
            "local E = setmetatable({ Behavior = function() end, class = function() return {} end, print = function() end }, { __index = _G })\nlocal reloaded, value, callback = false, 0, nil\nlocal adds, removes = 0, 0\nlocal buff = { SetValue = function(_, coefficient) value = coefficient end }\nlocal weapon = { DamageBuffedCoff = {\n    AddBuff = function(_, x) assert(x == buff); adds = adds + 1 end,\n    RemoveBuff = function(_, x) assert(x == buff); removes = removes + 1 end,\n} }\nE.WeaponAPI = {\n    GetWeapon = function(_, i) assert(i == 0); return weapon end,\n    IsReloaded = function(_) return reloaded end,\n    OnFired = function(_, _, cb) callback = cb end,\n}\nE.BuffAPI = { CreateValueBuff = function() return buff end }\n\nlocal B = assert(loadfile('../../Docs/Manual/tutorials/lua-api2-charged-shot/example.lua', 't', E))()\nlocal function instance(t) return setmetatable(t, { __index = B }) end\nlocal script = { SetUpdateInterval = function(_, x) assert(x == 0.1) end }\nlocal instance = instance({ script = script, chargeTime = 4, maxBonus = 0.5 })\ninstance:OnUpdated(1)\ninstance:OnVehicleReady({})\ninstance:OnUpdated(2)\nassert(value == 0 and adds == 1)\nreloaded = true\ninstance:OnUpdated(2)\nassert(value == 0.25)\ninstance:OnUpdated(5)\nassert(value == 0.5)\ncallback()\nassert(value == 0)\nreloaded = false\ninstance:OnUpdated(1)\nassert(value == 0)\ninstance:OnDestroyed()\nassert(removes == 1)\nlocal realBuff = CS.ShanghaiWindy.Core.API.BuffAPI.CreateValueBuff(\"Example\", false, 0)\nrealBuff:SetValue(0.5)\nassert(realBuff:GetValue() == 0.5)\nreturn \"Lua example passed\"\n",
            "manual-lua-api2-charged-shot",
            "null"
          ]
        },
        "expect": {
          "contains": "Lua example passed"
        }
      }
    ]
    
    In this article
    Back to top Panzer War Document