Skip to content

引擎 API 快速参考

首页 | 引擎 API 快速参考


最常用 DayZ 引擎方法的精简单页参考。有关详细说明和示例,请参阅各节标题中链接的完整章节。


目录


实体方法

完整参考:第 6.1 章:实体系统

位置与朝向(Object)

方法签名描述
GetPositionvector GetPosition()世界位置
SetPositionvoid SetPosition(vector pos)设置世界位置
GetOrientationvector GetOrientation()偏航、俯仰、翻滚(角度)
SetOrientationvoid SetOrientation(vector ori)设置偏航、俯仰、翻滚
GetDirectionvector GetDirection()前方向量
SetDirectionvoid SetDirection(vector dir)设置前方向
GetScalefloat GetScale()当前缩放
SetScalevoid SetScale(float scale)设置缩放

变换(IEntity)

方法签名描述
GetOriginvector GetOrigin()世界位置(引擎级别)
SetOriginvoid SetOrigin(vector orig)设置世界位置(引擎级别)
GetYawPitchRollvector GetYawPitchRoll()以偏航/俯仰/翻滚表示的旋转
GetTransformvoid GetTransform(out vector mat[4])完整 4x3 变换矩阵
SetTransformvoid SetTransform(vector mat[4])设置完整变换
VectorToParentvector VectorToParent(vector vec)本地方向转世界方向
CoordToParentvector CoordToParent(vector coord)本地点转世界点
VectorToLocalvector VectorToLocal(vector vec)世界方向转本地方向
CoordToLocalvector CoordToLocal(vector coord)世界点转本地点

层级(IEntity)

方法签名描述
AddChildvoid AddChild(IEntity child, int pivot, bool posOnly = false)将子对象附加到骨骼
RemoveChildvoid RemoveChild(IEntity child, bool keepTransform = false)分离子对象
GetParentIEntity GetParent()父实体或 null
GetChildrenIEntity GetChildren()第一个子实体
GetSiblingIEntity GetSibling()下一个兄弟实体

显示信息(Object)

方法签名描述
GetTypestring GetType()配置类名(例如 "AKM"
GetDisplayNamestring GetDisplayName()本地化显示名称
IsKindOfbool IsKindOf(string type)检查配置继承

骨骼位置(Object)

方法签名描述
GetBonePositionLSvector GetBonePositionLS(int pivot)本地空间骨骼位置
GetBonePositionMSvector GetBonePositionMS(int pivot)模型空间骨骼位置
GetBonePositionWSvector GetBonePositionWS(int pivot)世界空间骨骼位置

配置访问(Object)

方法签名描述
ConfigGetBoolbool ConfigGetBool(string entry)从配置读取 bool
ConfigGetIntint ConfigGetInt(string entry)从配置读取 int
ConfigGetFloatfloat ConfigGetFloat(string entry)从配置读取 float
ConfigGetStringstring ConfigGetString(string entry)从配置读取 string
ConfigGetTextArrayvoid ConfigGetTextArray(string entry, out TStringArray values)读取字符串数组
ConfigIsExistingbool ConfigIsExisting(string entry)检查配置条目是否存在

生命值与伤害

完整参考:第 6.1 章:实体系统

方法签名描述
GetHealthfloat GetHealth(string zone, string type)获取生命值
GetMaxHealthfloat GetMaxHealth(string zone, string type)获取最大生命值
SetHealthvoid SetHealth(string zone, string type, float value)设置生命值
SetHealthMaxvoid SetHealthMax(string zone, string type)设为最大值
AddHealthvoid AddHealth(string zone, string type, float value)增加生命值
DecreaseHealthvoid DecreaseHealth(string zone, string type, float value, bool auto_delete = false)减少生命值
SetAllowDamagevoid SetAllowDamage(bool val)启用/禁用伤害
GetAllowDamagebool GetAllowDamage()检查是否允许伤害
IsAlivebool IsAlive()存活检查(在 EntityAI 上使用)
ProcessDirectDamagevoid ProcessDirectDamage(int dmgType, EntityAI source, string component, string ammoType, vector modelPos, float coef = 1.0, int flags = 0)应用伤害(EntityAI)

常用 zone/type 组合: ("", "Health") 全局,("", "Blood") 玩家血量,("", "Shock") 玩家休克,("Engine", "Health") 载具引擎。


类型检查

方法描述
IsMan()Object这是玩家吗?
IsBuilding()Object这是建筑吗?
IsTransport()Object这是载具吗?
IsDayZCreature()Object这是生物(僵尸/动物)吗?
IsKindOf(string)Object配置继承检查
IsItemBase()EntityAI这是背包物品吗?
IsWeapon()EntityAI这是武器吗?
IsMagazine()EntityAI这是弹匣吗?
IsClothing()EntityAI这是衣物吗?
IsFood()EntityAI这是食物吗?
Class.CastTo(out, obj)Class安全向下转型(返回 bool)
ClassName.Cast(obj)Class内联转型(失败返回 null)

背包

完整参考:第 6.1 章:实体系统

方法签名描述
GetInventoryGameInventory GetInventory()获取背包组件(EntityAI)
CreateInInventoryEntityAI CreateInInventory(string type)在货物中创建物品
CreateEntityInCargoEntityAI CreateEntityInCargo(string type)在货物中创建物品
CreateAttachmentEntityAI CreateAttachment(string type)作为附件创建物品
EnumerateInventoryvoid EnumerateInventory(int traversal, out array<EntityAI> items)列出所有物品
CountInventoryint CountInventory()计算物品数量
HasEntityInInventorybool HasEntityInInventory(EntityAI item)检查物品是否存在
AttachmentCountint AttachmentCount()附件数量
GetAttachmentFromIndexEntityAI GetAttachmentFromIndex(int idx)按索引获取附件
FindAttachmentByNameEntityAI FindAttachmentByName(string slot)按插槽获取附件

实体创建与删除

完整参考:第 6.1 章:实体系统

方法签名描述
CreateObjectObject GetGame().CreateObject(string type, vector pos, bool local = false, bool ai = false, bool physics = true)创建实体
CreateObjectExObject GetGame().CreateObjectEx(string type, vector pos, int flags, int rotation = RF_DEFAULT)使用 ECE 标志创建
ObjectDeletevoid GetGame().ObjectDelete(Object obj)服务端立即删除
ObjectDeleteOnClientvoid GetGame().ObjectDeleteOnClient(Object obj)仅客户端删除
Deletevoid obj.Delete()延迟删除(下一帧)

常用 ECE 标志

标志描述
ECE_NONE0无特殊行为
ECE_CREATEPHYSICS1024创建碰撞
ECE_INITAI2048初始化 AI
ECE_EQUIP24576带附件和货物生成
ECE_PLACE_ON_SURFACE组合值物理 + 路径 + 射线检测
ECE_LOCAL1073741824仅客户端(不同步)
ECE_NOLIFETIME4194304不会消失
ECE_KEEPHEIGHT524288保持 Y 位置

玩家方法

完整参考:第 6.1 章:实体系统

方法签名描述
GetIdentityPlayerIdentity GetIdentity()玩家身份对象
GetIdentity().GetName()string GetName()Steam/平台显示名
GetIdentity().GetId()string GetId()BI 唯一 ID
GetIdentity().GetPlainId()string GetPlainId()Steam64 ID
GetIdentity().GetPlayerId()int GetPlayerId()会话玩家 ID
GetHumanInventory().GetEntityInHands()EntityAI GetEntityInHands()手中物品
GetDrivingVehicleEntityAI GetDrivingVehicle()正在驾驶的载具
IsAlivebool IsAlive()存活检查
IsUnconsciousbool IsUnconscious()昏迷检查
IsRestrainedbool IsRestrained()被束缚检查
IsInVehiclebool IsInVehicle()是否在载具中
SpawnEntityOnGroundOnCursorDirEntityAI SpawnEntityOnGroundOnCursorDir(string type, float dist)在玩家前方生成

载具方法

完整参考:第 6.2 章:载具系统

乘员(Transport)

方法签名描述
CrewSizeint CrewSize()总座位数
CrewMemberHuman CrewMember(int idx)获取座位上的人员
CrewMemberIndexint CrewMemberIndex(Human member)获取人员的座位
CrewGetOutvoid CrewGetOut(int idx)强制弹出座位
CrewDeathvoid CrewDeath(int idx)击杀乘员

引擎(Car)

方法签名描述
EngineIsOnbool EngineIsOn()引擎是否运行?
EngineStartvoid EngineStart()启动引擎
EngineStopvoid EngineStop()停止引擎
EngineGetRPMfloat EngineGetRPM()当前转速
EngineGetRPMRedlinefloat EngineGetRPMRedline()红线转速
GetGearint GetGear()当前档位
GetSpeedometerfloat GetSpeedometer()速度(千米/时)

流体(Car)

方法签名描述
GetFluidCapacityfloat GetFluidCapacity(CarFluid fluid)最大容量
GetFluidFractionfloat GetFluidFraction(CarFluid fluid)填充水平 0.0-1.0
Fillvoid Fill(CarFluid fluid, float amount)添加流体
Leakvoid Leak(CarFluid fluid, float amount)移除流体
LeakAllvoid LeakAll(CarFluid fluid)排空所有流体

CarFluid 枚举: FUEL, OIL, BRAKE, COOLANT

控制(Car)

方法签名描述
SetBrakevoid SetBrake(float value, int wheel = -1)0.0-1.0,-1 = 所有车轮
SetHandbrakevoid SetHandbrake(float value)0.0-1.0
SetSteeringvoid SetSteering(float value, bool analog = true)转向输入
SetThrustvoid SetThrust(float value, int wheel = -1)0.0-1.0 油门

天气方法

完整参考:第 6.3 章:天气系统

访问

方法签名描述
GetGame().GetWeather()Weather GetWeather()获取天气单例

现象(Weather)

方法签名描述
GetOvercastWeatherPhenomenon GetOvercast()云量
GetRainWeatherPhenomenon GetRain()降雨
GetFogWeatherPhenomenon GetFog()
GetSnowfallWeatherPhenomenon GetSnowfall()降雪
GetWindMagnitudeWeatherPhenomenon GetWindMagnitude()风速
GetWindDirectionWeatherPhenomenon GetWindDirection()风向
GetWindvector GetWind()风向向量
GetWindSpeedfloat GetWindSpeed()风速(米/秒)
SetStormvoid SetStorm(float density, float threshold, float timeout)闪电配置

WeatherPhenomenon

方法签名描述
GetActualfloat GetActual()当前插值后的值
GetForecastfloat GetForecast()目标值
GetDurationfloat GetDuration()剩余持续时间(秒)
Setvoid Set(float forecast, float time = 0, float minDuration = 0)设置目标(仅服务端)
SetLimitsvoid SetLimits(float min, float max)值范围限制
SetTimeLimitsvoid SetTimeLimits(float min, float max)变化速度限制
SetChangeLimitsvoid SetChangeLimits(float min, float max)变化幅度限制

文件 I/O 方法

完整参考:第 6.8 章:文件 I/O 与 JSON

路径前缀

前缀位置可写
$profile:服务端/客户端配置目录
$saves:存档目录
$mission:当前任务文件夹通常只读
$CurrentDir:工作目录视情况而定

文件操作

方法签名描述
FileExistbool FileExist(string path)检查文件是否存在
MakeDirectorybool MakeDirectory(string path)创建目录
OpenFileFileHandle OpenFile(string path, FileMode mode)打开文件(0 = 失败)
CloseFilevoid CloseFile(FileHandle fh)关闭文件
FPrintvoid FPrint(FileHandle fh, string text)写入文本(无换行)
FPrintlnvoid FPrintln(FileHandle fh, string text)写入文本 + 换行
FGetsint FGets(FileHandle fh, string line)读取一行
ReadFilestring ReadFile(FileHandle fh)读取整个文件
DeleteFilebool DeleteFile(string path)删除文件
CopyFilebool CopyFile(string src, string dst)复制文件

JSON(JsonFileLoader)

方法签名描述
JsonLoadFilevoid JsonFileLoader<T>.JsonLoadFile(string path, T obj)将 JSON 加载到对象中(返回 void
JsonSaveFilevoid JsonFileLoader<T>.JsonSaveFile(string path, T obj)将对象保存为 JSON

FileMode 枚举

描述
FileMode.READ以读取方式打开
FileMode.WRITE以写入方式打开(创建/覆盖)
FileMode.APPEND以追加方式打开

定时器与 CallQueue 方法

完整参考:第 6.7 章:定时器与 CallQueue

访问

表达式返回值描述
GetGame().GetCallQueue(CALL_CATEGORY_GAMEPLAY)ScriptCallQueue游戏玩法调用队列
GetGame().GetCallQueue(CALL_CATEGORY_SYSTEM)ScriptCallQueue系统调用队列
GetGame().GetCallQueue(CALL_CATEGORY_GUI)ScriptCallQueueGUI 调用队列
GetGame().GetUpdateQueue(CALL_CATEGORY_GAMEPLAY)ScriptInvoker每帧更新队列

ScriptCallQueue

方法签名描述
CallLatervoid CallLater(func fn, int delay = 0, bool repeat = false, param1..4)调度延迟/重复调用
Callvoid Call(func fn, param1..4)下一帧执行
CallByNamevoid CallByName(Class obj, string fnName, int delay = 0, bool repeat = false, Param par = null)按字符串名称调用方法
Removevoid Remove(func fn)取消已调度的调用
RemoveByNamevoid RemoveByName(Class obj, string fnName)按字符串名称取消
GetRemainingTimefloat GetRemainingTime(Class obj, string fnName)获取 CallLater 的剩余时间

Timer 类

方法签名描述
Timer()void Timer(int category = CALL_CATEGORY_SYSTEM)构造函数
Runvoid Run(float duration, Class obj, string fnName, Param params = null, bool loop = false)启动定时器
Stopvoid Stop()停止定时器
Pausevoid Pause()暂停定时器
Continuevoid Continue()恢复定时器
IsPausedbool IsPaused()定时器是否暂停?
IsRunningbool IsRunning()定时器是否活动?
GetRemainingfloat GetRemaining()剩余秒数

ScriptInvoker

方法签名描述
Insertvoid Insert(func fn)注册回调
Removevoid Remove(func fn)取消注册回调
Invokevoid Invoke(params...)触发所有回调
Countint Count()已注册回调数
Clearvoid Clear()移除所有回调

控件创建方法

完整参考:第 3.5 章:编程创建

方法签名描述
GetGame().GetWorkspace()WorkspaceWidget GetWorkspace()获取 UI 工作区
CreateWidgetsWidget CreateWidgets(string layout, Widget parent = null)加载 .layout 文件
FindAnyWidgetWidget FindAnyWidget(string name)按名称查找子控件(递归)
Showvoid Show(bool show)显示/隐藏控件
SetTextvoid TextWidget.SetText(string text)设置文本内容
SetImagevoid ImageWidget.SetImage(int index)设置图片索引
SetColorvoid SetColor(int color)设置控件颜色(ARGB)
SetAlphavoid SetAlpha(float alpha)设置透明度 0.0-1.0
SetSizevoid SetSize(float x, float y, bool relative = false)设置控件大小
SetPosvoid SetPos(float x, float y, bool relative = false)设置控件位置
GetScreenSizevoid GetScreenSize(out float x, out float y)屏幕分辨率
Destroyvoid Widget.Destroy()移除并销毁控件

ARGB 颜色辅助函数

函数签名描述
ARGBint ARGB(int a, int r, int g, int b)创建颜色整数(每个 0-255)
ARGBFint ARGBF(float a, float r, float g, float b)创建颜色整数(每个 0.0-1.0)

RPC / 网络方法

完整参考:第 6.9 章:网络与 RPC

环境检查

方法签名描述
GetGame().IsServer()bool IsServer()在服务端/监听服务器主机上为 true
GetGame().IsClient()bool IsClient()在客户端为 true
GetGame().IsMultiplayer()bool IsMultiplayer()在多人游戏中为 true
GetGame().IsDedicatedServer()bool IsDedicatedServer()仅在专用服务器上为 true

ScriptRPC

方法签名描述
ScriptRPC()void ScriptRPC()构造函数
Writebool Write(void value)序列化一个值(int, float, bool, string, vector, array)
Sendvoid Send(Object target, int rpc_type, bool guaranteed, PlayerIdentity recipient = null)发送 RPC
Resetvoid Reset()清除已写入的数据

接收(在 Object 上覆盖)

方法签名描述
OnRPCvoid OnRPC(PlayerIdentity sender, int rpc_type, ParamsReadContext ctx)RPC 接收处理器

ParamsReadContext

方法签名描述
Readbool Read(out void value)反序列化一个值(与 Write 相同的类型)

传统 RPC(CGame)

方法签名描述
RPCSingleParamvoid GetGame().RPCSingleParam(Object target, int rpc, Param param, bool guaranteed, PlayerIdentity recipient = null)发送单个 Param 对象
RPCvoid GetGame().RPC(Object target, int rpc, array<Param> params, bool guaranteed, PlayerIdentity recipient = null)发送多个 Params

ScriptInputUserData(输入验证)

方法签名描述
CanStoreInputUserDatabool ScriptInputUserData.CanStoreInputUserData()检查队列是否有空间
Writebool Write(void value)序列化值
Sendvoid Send()发送到服务端(仅客户端)

数学常量与方法

完整参考:第 1.7 章:数学与向量

常量

常量描述
Math.PI3.14159...圆周率
Math.PI26.28318...2 * Pi
Math.PI_HALF1.57079...Pi / 2
Math.DEG2RAD0.01745...角度转弧度乘数
Math.RAD2DEG57.2957...弧度转角度乘数
int.MAX2147483647最大整数
int.MIN-2147483648最小整数
float.MAX3.4028e+38最大浮点数
float.MIN1.175e-38最小正浮点数

随机数

方法签名描述
Math.RandomIntint RandomInt(int min, int max)随机整数 [min, max)
Math.RandomIntInclusiveint RandomIntInclusive(int min, int max)随机整数 [min, max]
Math.RandomFloat01float RandomFloat01()随机浮点数 [0, 1]
Math.RandomBoolbool RandomBool()随机 true/false

四舍五入

方法签名描述
Math.Roundfloat Round(float f)四舍五入到最近
Math.Floorfloat Floor(float f)向下取整
Math.Ceilfloat Ceil(float f)向上取整

限制与插值

方法签名描述
Math.Clampfloat Clamp(float val, float min, float max)限制在范围内
Math.Minfloat Min(float a, float b)两者中的最小值
Math.Maxfloat Max(float a, float b)两者中的最大值
Math.Lerpfloat Lerp(float a, float b, float t)线性插值
Math.InverseLerpfloat InverseLerp(float a, float b, float val)反向线性插值

绝对值与幂

方法签名描述
Math.AbsFloatfloat AbsFloat(float f)绝对值(浮点数)
Math.AbsIntint AbsInt(int i)绝对值(整数)
Math.Powfloat Pow(float base, float exp)
Math.Sqrtfloat Sqrt(float f)平方根
Math.SqrFloatfloat SqrFloat(float f)平方(f * f)

三角函数(弧度)

方法签名描述
Math.Sinfloat Sin(float rad)正弦
Math.Cosfloat Cos(float rad)余弦
Math.Tanfloat Tan(float rad)正切
Math.Asinfloat Asin(float val)反正弦
Math.Acosfloat Acos(float val)反余弦
Math.Atan2float Atan2(float y, float x)从分量计算角度

平滑阻尼

方法签名描述
Math.SmoothCDfloat SmoothCD(float val, float target, inout float velocity, float smoothTime, float maxSpeed, float dt)平滑趋近目标(类似 Unity 的 SmoothDamp)
c
// 平滑阻尼用法
// val:当前值,target:目标值,velocity:引用速度(在调用间持久化)
// smoothTime:平滑时间,maxSpeed:速度上限,dt:增量时间
float m_Velocity = 0;
float result = Math.SmoothCD(current, target, m_Velocity, 0.3, 1000.0, dt);

角度

方法签名描述
Math.NormalizeAnglefloat NormalizeAngle(float deg)归一化到 0-360

向量方法

方法签名描述
vector.Distancefloat Distance(vector a, vector b)两点间距离
vector.DistanceSqfloat DistanceSq(vector a, vector b)距离的平方(更快)
vector.Directionvector Direction(vector from, vector to)方向向量
vector.Dotfloat Dot(vector a, vector b)点积
vector.Lerpvector Lerp(vector a, vector b, float t)位置插值
v.Length()float Length()向量长度
v.LengthSq()float LengthSq()长度的平方(更快)
v.Normalized()vector Normalized()单位向量
v.VectorToAngles()vector VectorToAngles()方向转偏航/俯仰
v.AnglesToVector()vector AnglesToVector()偏航/俯仰转方向
v.Multiply3vector Multiply3(vector mat[3])矩阵乘法
v.InvMultiply3vector InvMultiply3(vector mat[3])逆矩阵乘法
Vector(x, y, z)vector Vector(float x, float y, float z)创建向量

全局函数

函数签名描述
GetGame()CGame GetGame()游戏实例
GetGame().GetPlayer()Man GetPlayer()本地玩家(仅客户端)
GetGame().GetPlayers(out arr)void GetPlayers(out array<Man> arr)所有玩家(服务端)
GetGame().GetWorld()World GetWorld()世界实例
GetGame().GetTickTime()float GetTickTime()服务器时间(秒)
GetGame().GetWorkspace()WorkspaceWidget GetWorkspace()UI 工作区
GetGame().SurfaceY(x, z)float SurfaceY(float x, float z)指定位置的地形高度
GetGame().SurfaceGetType(x, z)string SurfaceGetType(float x, float z)地表材质类型
GetGame().GetObjectsAtPosition(pos, radius, objects, proxyCargo)void GetObjectsAtPosition(vector pos, float radius, out array<Object> objects, out array<CargoBase> proxyCargo)查找附近物体
GetScreenSize(w, h)void GetScreenSize(out int w, out int h)获取屏幕分辨率
GetGame().IsServer()bool IsServer()服务端检查
GetGame().IsClient()bool IsClient()客户端检查
GetGame().IsMultiplayer()bool IsMultiplayer()多人游戏检查
Print(string)void Print(string msg)写入脚本日志
ErrorEx(string)void ErrorEx(string msg, ErrorExSeverity sev = ERROR)带严重级别的日志错误
DumpStackString()string DumpStackString()获取调用栈字符串
string.Format(fmt, ...)string Format(string fmt, ...)格式化字符串(%1..%9

任务钩子

完整参考:第 6.11 章:任务钩子

服务端(modded MissionServer)

方法描述
override void OnInit()初始化管理器,注册 RPC
override void OnMissionStart()所有模组加载后
override void OnUpdate(float timeslice)每帧(使用累加器!)
override void OnMissionFinish()清理单例,取消订阅事件
override void OnEvent(EventType eventTypeId, Param params)聊天、语音事件
override void InvokeOnConnect(PlayerBase player, PlayerIdentity identity)玩家加入
override void InvokeOnDisconnect(PlayerBase player)玩家离开
override void OnClientReadyEvent(int peerId, PlayerIdentity identity)客户端准备好接收数据
override void PlayerRegistered(int peerId)身份已注册

客户端(modded MissionGameplay)

方法描述
override void OnInit()初始化客户端管理器,创建 HUD
override void OnUpdate(float timeslice)客户端每帧更新
override void OnMissionFinish()清理
override void OnKeyPress(int key)按键按下
override void OnKeyRelease(int key)按键释放

动作系统

完整参考:第 6.12 章:动作系统

在物品上注册动作

c
override void SetActions()
{
    super.SetActions();
    AddAction(MyAction);           // 添加自定义动作
    RemoveAction(ActionEat);       // 移除原版动作
}

ActionBase 关键方法

方法描述
override void CreateConditionComponents()设置 CCINone/CCTNone 距离条件
override bool ActionCondition(...)自定义验证逻辑
override void OnExecuteServer(ActionData action_data)服务端执行
override void OnExecuteClient(ActionData action_data)客户端效果
override string GetText()显示名称(支持 #STR_ 键)

完整文档:首页 | 速查表 | 实体系统 | 载具 | 天气 | 定时器 | 文件 I/O | 网络 | 任务钩子 | 动作系统

Released under CC BY-SA 4.0 | Code examples under MIT License