Humanoid

Mostrar obsoleto

The Humanoid is a special object that gives models the functionality of a character. It grants the model with the ability to physically walk around and interact with various components of a Roblox experience. Humanoids are always parented inside of a Model, and the model is expected to be an assembly of BasePart and Motor6D; the root part of the assembly is expected to be named HumanoidRootPart. It also expects a part named Head to be connected to the character's torso part, either directly or indirectly. By default, there are two official types of character rigs supplied by Roblox, each with their own set of rules:

R6

  • A basic character rig that uses 6 parts for limbs.
  • The Head part must be attached to a part named Torso, or the Humanoid will die immediately.
  • BodyPart appearances are applied using CharacterMesh objects.
  • Certain properties, such as Humanoid.LeftLeg and Humanoid.RightLeg, only work with R6.

R15

  • More complex than R6, but also far more flexible and robust.
  • Uses 15 parts for limbs.
  • The Head part must be attached to a part named UpperTorso or the Humanoid will die immediately.
  • BodyPart appearances have to be assembled directly.
  • Can be dynamically rescaled by using special NumberValue objects parented inside of the Humanoid.
  • The Humanoid will automatically create Vector3Value objects named OriginalSize inside of each limb.
  • If a NumberValue is parented inside of the Humanoid and is named one of the following, it will be used to control the scaling functionality:
    • BodyDepthScale
    • BodyHeightScale
    • BodyWidthScale
    • HeadScale

Muestras de código

Walking Camera Bobble Effect

local RunService = game:GetService("RunService")
local playerModel = script.Parent
local humanoid = playerModel:WaitForChild("Humanoid")
local function updateBobbleEffect()
local now = tick()
if humanoid.MoveDirection.Magnitude > 0 then -- Is the character walking?
local velocity = humanoid.RootPart.Velocity
local bobble_X = math.cos(now * 9) / 5
local bobble_Y = math.abs(math.sin(now * 12)) / 5
local bobble = Vector3.new(bobble_X, bobble_Y, 0) * math.min(1, velocity.Magnitude / humanoid.WalkSpeed)
humanoid.CameraOffset = humanoid.CameraOffset:lerp(bobble, 0.25)
else
-- Scale down the CameraOffset so that it shifts back to its regular position.
humanoid.CameraOffset = humanoid.CameraOffset * 0.75
end
end
RunService.RenderStepped:Connect(updateBobbleEffect)

Resumen

Propiedades

Métodos

Eventos

Propiedades

AutoJumpEnabled

Leer paralelo

AutoJumpEnabled sets whether or not the Humanoid will attempt to automatically jump over an obstacle it is walking towards.

Currently, this property only works when the following conditions are true:

  • The Humanoid's character model is the Player.Character of a Player.
  • The Player in question is using touch controls.

When a player's character spawns, the property's value matches the player's Player.AutoJumpEnabled property - which in turn matches the StarterPlayer.AutoJumpEnabled property.

Muestras de código

Auto-Jump Toggle

local Players = game:GetService("Players")
local player = Players.LocalPlayer
local button = script.Parent
local function update()
-- Update button text
if player.AutoJumpEnabled then
button.Text = "Auto-Jump is ON"
else
button.Text = "Auto-Jump is OFF"
end
-- Reflect the property in the player's character, if they have one
if player.Character then
local human = player.Character:FindFirstChild("Humanoid")
if human then
human.AutoJumpEnabled = player.AutoJumpEnabled
end
end
end
local function onActivated()
-- Toggle auto-jump
player.AutoJumpEnabled = not player.AutoJumpEnabled
-- Update everything else
update()
end
button.Activated:Connect(onActivated)
update()

AutoRotate

Leer paralelo

The AutoRotate property describes whether or not the Humanoid will automatically rotate to face in the direction they are moving. When set to true, the character model will gradually turn to face their movement direction as the Humanoid walks around. When set to false, the character model will remain fixated in its current rotation, unless a rotating force is applied to the HumanoidRootPart.

If the character model happens to be the character of a player, then the behavior of the Humanoid's rotation is influenced by the UserGameSetting's RotateType property.

When the AutoRotate property is set to true, the RotateType property has the following effects on the Humanoid's rotation:

RotationTypeBehaviorContext
MovementRelative
CameraRelativeCharacter will rotate to face in the direction of the camera.Player has their camera zoomed into first-person, or they are in shift-lock mode.

Muestras de código

AutoRotate Button

local button = script.Parent
local enabled = true
local ON_COLOR = BrickColor.Green()
local OFF_COLOR = BrickColor.Red()
local function touchButton(humanoid)
if enabled then
enabled = false
button.BrickColor = OFF_COLOR
if humanoid.AutoRotate then
print(humanoid:GetFullName() .. " can no longer auto-rotate!")
humanoid.AutoRotate = false
else
print(humanoid:GetFullName() .. " can now auto-rotate!")
humanoid.AutoRotate = true
end
task.wait(1)
button.BrickColor = ON_COLOR
enabled = true
end
end
local function onTouched(hit)
local char = hit:FindFirstAncestorWhichIsA("Model")
if char then
local humanoid = char:FindFirstChildOfClass("Humanoid")
if humanoid then
touchButton(humanoid)
end
end
end
button.Touched:Connect(onTouched)
button.BrickColor = ON_COLOR

AutomaticScalingEnabled

Leer paralelo

The Humanoid has six child scale values including BodyDepthScale, BodyHeightScale, BodyProportionScale, BodyTypeScale, BodyWidthScale, HeadScale. Changing the value of any of these causes the character's body parts and accessories to change size, but only if AutomaticScalingEnabled is true.

BreakJointsOnDeath

Leer paralelo

Determines whether the humanoid's joints break when in the Enum.HumanoidStateType.Dead state. Defaults to true.

CameraOffset

Leer paralelo

The CameraOffset property specifies an offset to the camera's subject position when its Camera.CameraSubject is set to this Humanoid.

The offset is applied in object-space, relative to the orientation of the Humanoid's HumanoidRootPart. For example, an offset Vector3 value of (0, 10, 0) offsets the player's camera to 10 studs above the player's humanoid.

Muestras de código

Walking Camera Bobble Effect

local RunService = game:GetService("RunService")
local playerModel = script.Parent
local humanoid = playerModel:WaitForChild("Humanoid")
local function updateBobbleEffect()
local now = tick()
if humanoid.MoveDirection.Magnitude > 0 then -- Is the character walking?
local velocity = humanoid.RootPart.Velocity
local bobble_X = math.cos(now * 9) / 5
local bobble_Y = math.abs(math.sin(now * 12)) / 5
local bobble = Vector3.new(bobble_X, bobble_Y, 0) * math.min(1, velocity.Magnitude / humanoid.WalkSpeed)
humanoid.CameraOffset = humanoid.CameraOffset:lerp(bobble, 0.25)
else
-- Scale down the CameraOffset so that it shifts back to its regular position.
humanoid.CameraOffset = humanoid.CameraOffset * 0.75
end
end
RunService.RenderStepped:Connect(updateBobbleEffect)
Leer paralelo

The DisplayDistanceType property controls the distance behavior of the humanoid's name and health display. This property is set using the Enum.HumanoidDisplayDistanceType enum with three available values, each with their own set of rules:

  • When set to Viewer, the humanoid sees the name/health of other humanoids within range of its own NameDisplayDistance and HealthDisplayDistance.
  • When set to Subject, the humanoid takes full control over its own name and health display through its NameDisplayDistance and HealthDisplayDistance values.
  • When set to None, the humanoid's name and health bar do not appear under any circumstances.

See Character Name/Health Display for an in-depth guide on controlling the appearance of character names and health bars.

Muestras de código

Displaying a Humanoid's Health and Name

local humanoid = script.Parent
humanoid.DisplayDistanceType = Enum.HumanoidDisplayDistanceType.Viewer
humanoid.HealthDisplayDistance = 0
humanoid.NameDisplayDistance = 100

DisplayName

Leer paralelo

DisplayName is a property that determines the Humanoid's name display when visible. By default, a new Humanoid will have the value of an empty string. If DisplayName is an empty string, the humanoid's name display will default to the humanoid's parent's name property.

Player Character Loading

When players load their character, either automatically or through the use of LoadCharacter(), the Humanoid that is created by the engine will have its DisplayName property set to the player's DisplayName property.

StarterCharacter and StarterHumanoid

When a Humanoid named StarterHumanoid is parented to StarterPlayer, or when a Humanoid is present in a Model named StarterCharacter, the DisplayName property will be respected when Characters are loaded by Players in the game. The engine will only override the DisplayName property of the Humanoid with the DisplayName property of the player if the Humanoid.DisplayName of StarterHumanoid is an empty string.

EvaluateStateMachine

Leer paralelo

FloorMaterial

Solo lectura
No replicado
Leer paralelo

This is a read-only property that describes the Enum.Material the Humanoid is currently standing on. It works with both regular Parts and Terrain voxels.

The code sample below demonstrates how to listen to when this property changes using Object:GetPropertyChangedSignal(). When the material the humanoid is standing on changes, it will print a message indicating the new material being stood on.


local Humanoid = route.to.humanoid
Humanoid:GetPropertyChangedSignal("FloorMaterial"):Connect(function()
print("New value for FloorMaterial: " .. tostring(Humanoid.FloorMaterial))
end)

Caveats

  • When the Humanoid is not standing on a floor, the value of this property will be set to Air.
    • This occurs because Enum properties cannot have an empty value.
    • This can cause some confusion if a part has its material is set to Air, though in practice, parts are not supposed to use that material in the first place.
  • The character model of the Humanoid must be able to collide with the floor, or else it will not be detected.

Health

No replicado
Leer paralelo

This property represents the current health of the Humanoid. The value is restricted to the range between 0 and MaxHealth. If the humanoid is dead, this property is continually set to 0.

Note that the TakeDamage() function may be used to subtract from Health instead of setting the property directly.

Health Regeneration

By default, a passive health regeneration script is automatically inserted into humanoids. This causes non-dead player characters to regenerate 1% of MaxHealth each second. To disable this regeneration behavior, add an empty Script named Health to StarterCharacterScripts.

Health Bar Display

When Health is less than MaxHealth, a health bar is displayed in-experience. The display behavior of the health bar is dependent on the HealthDisplayDistance and HealthDisplayType.

See Character Name/Health Display for an in-depth guide on controlling the appearance of character names and health bars.

Death

When the value of the character's health reaches 0, the Humanoid automatically transitions to the Enum.HumanoidStateType.Dead state. In this state, Health is locked to 0; however, there is no error or warning for setting the Health of a dead humanoid to a positive nonzero value.

HealthDisplayDistance

Leer paralelo

This property is a number used in conjunction with the DisplayDistanceType property to control the distance from which a humanoid's health bar can be seen.

See Character Name/Health Display for an in-depth guide on controlling the appearance of character names and health bars.

Leer paralelo

This property controls when a humanoid's health bar is allowed to be displayed. By default, this property is set to DisplayWhenDamaged, which makes the health bar only display when a humanoid's Health is less than its MaxHealth. It can also be set to AlwaysOn, which makes the health bar always display, or AlwaysOff, which prevents it from ever displaying.

Note that this property functions independently of the humanoid's HealthDisplayDistance property which is responsible for making the health bar fade out at certain distances. If Humanoid.HealthDisplayType|HealthDisplayType is set to AlwaysOn, it will still fade out depending the how HealthDisplayDistance is configured.

See Character Name/Health Display for an in-depth guide on controlling the appearance of character names and health bars.

HipHeight

Leer paralelo

Determines the distance (in studs) off the ground the RootPart should be when the humanoid is standing. The RigType influences the way this property behaves.

For R15 rigs, a suitable hip height is preset to ensure the height of the RootPart is correct. The height of the legs is not used. The overall height of the humanoid can be described in the following formula:


Height = (0.5 * RootPart.Size.Y) + HipHeight

For R6 rigs, HipHeight instead describes a relative offset. The overall height of the humanoid can be described in the following formula:


Height = LeftLeg.Size.Y + (0.5 * RootPart.Size.Y) + HipHeight

Jump

No replicado
Leer paralelo

If true, the Humanoid jumps with an upwards force equal to the value of Humanoid.JumpPower or the height of Humanoid.JumpHeight, depending on the value of Humanoid.UseJumpPower.

JumpHeight

Leer paralelo

Provides control over the height a Humanoid jumps, in studs. The starting value of this property is determined by the value of StarterPlayer.CharacterJumpHeight which defaults to 7.2.

Although setting this property to 0 will effectively prevent the humanoid from jumping, it's recommended to disable jumping by disabling the Enum.HumanoidStateType.Jumping state through Humanoid:SetStateEnabled().

This property is only visible in the Properties window if Humanoid.UseJumpPower is set to false, as it would not be relevant otherwise (instead, Humanoid.JumpPower is used).

JumpPower

Leer paralelo

Determines how much upwards force is applied to the Humanoid when jumping. The starting value of this property is determined by the value of StarterPlayer.CharacterJumpPower which defaults to 50 and is constrained between 0 and 1000. Note that jumps are also influenced by the Workspace.Gravity property which determines the acceleration due to gravity.

Although setting this property to 0 will effectively prevent the humanoid from jumping, it's recommended to disable jumping by disabling the Enum.HumanoidStateType.Jumping state through Humanoid:SetStateEnabled().

This property is only visible in the Properties window if Humanoid.UseJumpPower is set to true, as it would not be relevant otherwise (instead, Humanoid.JumpHeight is used).

MaxHealth

Leer paralelo

The maximum value of a humanoid's Health.

The value of this property is used alongside the Health property to size the default health bar display. When a humanoid's Health reaches MaxHealth, its health bar may not be displayed, depending on its HealthDisplayType property.

MaxSlopeAngle

Leer paralelo

This property determines the maximum slope angle that a humanoid can climb. If the angle of a slope is greater than a humanoid's MaxSlopeAngle, they will slide down the slope.

When a character spawns, this property is set according to the value of StarterPlayer.CharacterMaxSlopeAngle.

The value of this property is constrained to values between 0° and 89°. It defaults to 89°, so humanoids can climb pretty much any slope they want by default.

Muestras de código

Limiting The Slope a Humanoid Can Walk Up

local player = game.Players.LocalPlayer
local char = player.CharacterAdded:wait()
local h = char:FindFirstChild("Humanoid")
h.MaxSlopeAngle = 30

MoveDirection

Solo lectura
No replicado
Leer paralelo

MoveDirection is a read-only property that describes the direction a Humanoid is walking in, as a unit vector or zero length vector. The direction is described in world space.

Because this property is read-only, it cannot be set by a Script or LocalScript.

Muestras de código

Walking Camera Bobble Effect

local RunService = game:GetService("RunService")
local playerModel = script.Parent
local humanoid = playerModel:WaitForChild("Humanoid")
local function updateBobbleEffect()
local now = tick()
if humanoid.MoveDirection.Magnitude > 0 then -- Is the character walking?
local velocity = humanoid.RootPart.Velocity
local bobble_X = math.cos(now * 9) / 5
local bobble_Y = math.abs(math.sin(now * 12)) / 5
local bobble = Vector3.new(bobble_X, bobble_Y, 0) * math.min(1, velocity.Magnitude / humanoid.WalkSpeed)
humanoid.CameraOffset = humanoid.CameraOffset:lerp(bobble, 0.25)
else
-- Scale down the CameraOffset so that it shifts back to its regular position.
humanoid.CameraOffset = humanoid.CameraOffset * 0.75
end
end
RunService.RenderStepped:Connect(updateBobbleEffect)

NameDisplayDistance

Leer paralelo

The NameDisplayDistance property is a number used in conjunction with the Humanoid.DisplayDistanceType property to control the distance from which a humanoid's name can be seen.

See Character Name/Health Display for an in-depth guide on controlling the appearance of character names and health bars.

NameOcclusion

Leer paralelo

Controls whether a humanoid's name and health bar can be seen behind walls or other objects. This property is a Enum.NameOcclusion value and can be configured to occlude all names, enemy names, or disable occlusion entirely.

In cases where the LocalPlayer has no Humanoid associated with it, this property instead applies to the subject Humanoid.

See Character Name/Health Display for an in-depth guide on controlling the appearance of character names and health bars.

Muestras de código

Occlude Player Names

local Players = game:GetService("Players")
local function onCharacterAdded(character)
local humanoid = character:WaitForChild("Humanoid")
humanoid.NamOcclusion = Enum.NameOcclusion.OccludeAll
end
local function onPlayerAdded(player)
player.CharacterAdded:Connect(onCharacterAdded)
end
Players.PlayerAdded:Connect(onPlayerAdded)

PlatformStand

Leer paralelo

Determines whether the Humanoid is currently in the Enum.HumanoidStateType.PlatformStanding state. When true, the Humanoid is in a state where it is free-falling and cannot move. This state behaves similar to sitting, except that jumping does not free the humanoid from the state.

RequiresNeck

Leer paralelo

Allows developers to disable the behavior where a player Character|character dies if the Neck Motor6D is removed or disconnected even momentarily. This property defaults to true.

Leer paralelo

RigType describes whether a Humanoid is utilizing the legacy R6 character rig, or the newer R15 character rig.

The R6 rig uses 6 visible Parts while the R15 rig uses 15 visible Parts. R15 rigs have more joints than R6 rigs, making them much more versatile when being animated.

Note that if this property is set incorrectly, the Humanoid will not function correctly. For example, if a R15 humanoid's RigType is set to R6, the Humanoid will die as there is no BasePart called Torso connected to a BasePart called Head.

RootPart

Solo lectura
No replicado
Leer paralelo

A reference to the humanoid's HumanoidRootPart object, the root driving part of the Humanoid that controls a humanoid's movement through the 3D world. This part is normally invisible.

Note that in the case of player characters, RootPart is the same as the Model.PrimaryPart of the Player.Character model.

SeatPart

Solo lectura
No replicado
Leer paralelo

SeatPart is a reference to the seat that a Humanoid is currently sitting in, if any. The value of this property can be either a Seat, or a VehicleSeat. It will be nil if the Humanoid is not currently sitting in a seat.

Note:

Sit

Leer paralelo

The Sit property is a boolean that indicates whether the Humanoid is currently sitting. Humanoids can be forced into a sitting state by setting this property's value to true. If the Humanoid isn't attached to a seat while in its sitting state, it will trip over with no collision in its legs. A Humanoid can escape from the sitting state by jumping.

Note:

TargetPoint

Leer paralelo

Do not use This property only works with Experimental Mode enabled, which has been entirely discontinued.

This property describes a 3D position in space where the Player controlling this Humanoid last clicked with a Tool equipped.

This property is primarily used by classic tools to determine what a humanoid is targeting when they activate a tool. If you give an NPC a classic rocket launcher, set their TargetPoint, and then call the tool's Tool:Activate() function, you can make the NPC fire a rocket at the target point.

UseJumpPower

Leer paralelo

When a character spawns, this property is set according to the value of StarterPlayer.CharacterUseJumpPower which defaults to true.

When jumping, with this set to true, the Humanoid.JumpHeight value is used to ensure the humanoid jumps to that height. With this set to false, the Humanoid.JumpPower value is used to apply an upward force.

WalkSpeed

Leer paralelo

This property describes how quickly the Humanoid is able to walk, in studs per second. It defaults to the value of StarterPlayer.CharacterWalkSpeed (16), meaning a player character can move 16 studs in any direction each second.

Notes

  • When controlled on a mobile device or a gamepad, a humanoid can walk slower than its WalkSpeed if the controlling thumbstick is moved just a gradual degree from center.
  • You can freeze a humanoid in place by setting WalkSpeed to 0; this prevents the controlling player from moving it through the default movement mechanisms.
  • The default animation script scales a humanoid's movement animations based on how fast it is moving relative to the default speed of 16 studs/second.
  • The speed at which the Humanoid is currently walking can be obtained using the Running event.

WalkToPart

Leer paralelo

WalkToPart is a reference to a part that the Humanoid is trying to reach. This property is normally set when a part is passed as the 2nd argument of the Humanoid's Humanoid:MoveTo() function.

When WalkToPart is set and a humanoid is actively trying to reach the part, it will keep updating its Vector3 goal to be the position of the part, plus the Humanoid.WalkToPoint translated in object space relative to the rotation of the part.

This can be described in Lua as:


goal = humanoid.WalkToPart.CFrame:pointToObjectSpace(humanoid.WalkToPoint)

Caveats

  • Setting the value of WalkToPart isn't sufficient enough to make a humanoid start following a part.
  • The Humanoid is prompted to start attempting to reach a goal when the value of WalkToPoint is changed.
  • This may be changed in the future.
  • The reach goal state of a humanoid will timeout after 8 seconds if it doesn't reach its goal.
  • This is done so that NPCs won't get stuck waiting for Humanoid.MoveToFinished to fire.
  • If you don't want this to happen, you should repeatedly call MoveTo so that the timeout will keep resetting.

WalkToPoint

Leer paralelo

WalkToPoint describes the 3D position in space that a humanoid is trying to reach, after having been prompted to do so by the Humanoid's Humanoid:MoveTo() function.

If a humanoid's Humanoid.WalkToPart is set, the goal is set by transforming WalkToPoint relative to the parts position and rotation. If WalkToPart is not set, then the humanoid will try to reach the 3D position specified by WalkToPoint directly.

Caveats

  • The value of WalkToPoint must be changed to a different value in order for the humanoid to start walking towards it.
  • If you want to make a humanoid walk to 0,0,0, you should use the Humanoid's MoveTo function.
  • This may be changed in the future.
  • The reach goal state of a humanoid will timeout after 8 seconds if it doesn't reach its goal.
  • This is done so that NPCs won't get stuck waiting for Humanoid.MoveToFinished to fire.
  • If you don't want this to happen, you should repeatedly call MoveTo so that the timeout will keep resetting.

Muestras de código

Humanoid MoveTo Without Time out

local function moveTo(humanoid, targetPoint, andThen)
local targetReached = false
-- listen for the humanoid reaching its target
local connection
connection = humanoid.MoveToFinished:Connect(function(reached)
targetReached = true
connection:Disconnect()
connection = nil
if andThen then
andThen(reached)
end
end)
-- start walking
humanoid:MoveTo(targetPoint)
-- execute on a new thread so as to not yield function
task.spawn(function()
while not targetReached do
-- does the humanoid still exist?
if not (humanoid and humanoid.Parent) then
break
end
-- has the target changed?
if humanoid.WalkToPoint ~= targetPoint then
break
end
-- refresh the timeout
humanoid:MoveTo(targetPoint)
task.wait(6)
end
-- disconnect the connection if it is still connected
if connection then
connection:Disconnect()
connection = nil
end
end)
end
local function andThen(reached)
print((reached and "Destination reached!") or "Failed to reach destination!")
end
moveTo(script.Parent:WaitForChild("Humanoid"), Vector3.new(50, 0, 50), andThen)

Métodos

AddAccessory

void

This method attaches the specified Accessory to the humanoid's parent.

When this method is called, an Accessory is attached to the character by searching for an Attachment in the humanoid's parent that shares the same name as an Attachment in the accessory's Handle Part. If one is found, the Handle part will be connected to the parent of the Attachment using a Weld, and the weld will be configured so the Attachments occupy the same space.

If the required Attachment can not be found, then the Accessory will remain parented to the humanoid's parent but it will be unattached.

Typically, accessory welds are created on the server, but they can be created on the client under certain circumstances. In these situations, client-sided calls to AddAccessory() may not always produce the desired behavior and you can use BuildRigFromAttachments() to force the expected weld creation.

Parámetros

accessory: Instance

The Accessory to be attached.


Devuelve

void

Muestras de código

[Humanoid] AddAccessory Example

local playerModel = script.Parent
local humanoid = playerModel:WaitForChild("Humanoid")
local clockworksShades = Instance.new("Accessory")
clockworksShades.Name = "ClockworksShades"
local handle = Instance.new("Part")
handle.Name = "Handle"
handle.Size = Vector3.new(1, 1.6, 1)
handle.Parent = clockworksShades
local faceFrontAttachment = Instance.new("Attachment")
faceFrontAttachment.Name = "FaceFrontAttachment"
faceFrontAttachment.Position = Vector3.new(0, -0.24, -0.45)
faceFrontAttachment.Parent = handle
local mesh = Instance.new("SpecialMesh")
mesh.Name = "Mesh"
mesh.Scale = Vector3.new(1, 1.3, 1)
mesh.MeshId = "rbxassetid://1577360"
mesh.TextureId = "rbxassetid://1577349"
mesh.Parent = handle
humanoid:AddAccessory(clockworksShades)

BuildRigFromAttachments

void

This method assembles a tree of Motor6D joints for the Humanoid. Motor6D joints are required for the playback of Animations.

Starting from the humanoid's RootPart, this method collects all Attachments parented in the current part whose name ends with RigAttachment. It then searches for a matching attachment in the character that shares the same name as the attachment. Using those two attachments, a Motor6D joint is generated based on the parts associated with the two attachments and the CFrame of the attachments.

Humanoid:BuildRigFromAttachments() also scales the character and sets body colors.


Devuelve

void

Muestras de código

Lua Port of BuildRigFromAttachments

local function createJoint(jointName, att0, att1)
local part0, part1 = att0.Parent, att1.Parent
local newMotor = part1:FindFirstChild(jointName)
if not (newMotor and newMotor:IsA("Motor6D")) then
newMotor = Instance.new("Motor6D")
end
newMotor.Name = jointName
newMotor.Part0 = part0
newMotor.Part1 = part1
newMotor.C0 = att0.CFrame
newMotor.C1 = att1.CFrame
newMotor.Parent = part1
end
local function buildJointsFromAttachments(part, characterParts)
if not part then
return
end
-- first, loop thru all of the part's children to find attachments
for _, attachment in pairs(part:GetChildren()) do
if attachment:IsA("Attachment") then
-- only do joint build from "RigAttachments"
local attachmentName = attachment.Name
local findPos = attachmentName:find("RigAttachment")
if findPos then
-- also don't make double joints (there is the same named
-- rigattachment under two parts)
local jointName = attachmentName:sub(1, findPos - 1)
if not part:FindFirstChild(jointName) then
-- try to find other part with same rig attachment name
for _, characterPart in pairs(characterParts) do
if part ~= characterPart then
local matchingAttachment = characterPart:FindFirstChild(attachmentName)
if matchingAttachment and matchingAttachment:IsA("Attachment") then
createJoint(jointName, attachment, matchingAttachment)
buildJointsFromAttachments(characterPart, characterParts)
break
end
end
end
end
end
end
end
end
local function buildRigFromAttachments(humanoid)
local rootPart = humanoid.RootPart
assert(rootPart, "Humanoid has no HumanoidRootPart.")
local characterParts = {}
for _, descendant in ipairs(humanoid.Parent:GetDescendants()) do
if descendant:IsA("BasePart") then
table.insert(characterParts, descendant)
end
end
buildJointsFromAttachments(rootPart, characterParts)
end
local humanoid = script.Parent:WaitForChild("Humanoid")
buildRigFromAttachments(humanoid)
R15 Package Importer

local AssetService = game:GetService("AssetService")
local InsertService = game:GetService("InsertService")
local MarketplaceService = game:GetService("MarketplaceService")
local PACKAGE_ASSET_ID = 193700907 -- Circuit Breaker
local function addAttachment(part, name, position, orientation)
local attachment = Instance.new("Attachment")
attachment.Name = name
attachment.Parent = part
if position then
attachment.Position = position
end
if orientation then
attachment.Orientation = orientation
end
return attachment
end
local function createBaseCharacter()
local character = Instance.new("Model")
local humanoid = Instance.new("Humanoid")
humanoid.Parent = character
local rootPart = Instance.new("Part")
rootPart.Name = "HumanoidRootPart"
rootPart.Size = Vector3.new(2, 2, 1)
rootPart.Transparency = 1
rootPart.Parent = character
addAttachment(rootPart, "RootRigAttachment")
local head = Instance.new("Part")
head.Name = "Head"
head.Size = Vector3.new(2, 1, 1)
head.Parent = character
local headMesh = Instance.new("SpecialMesh")
headMesh.Scale = Vector3.new(1.25, 1.25, 1.25)
headMesh.MeshType = Enum.MeshType.Head
headMesh.Parent = head
local face = Instance.new("Decal")
face.Name = "face"
face.Texture = "rbxasset://textures/face.png"
face.Parent = head
addAttachment(head, "FaceCenterAttachment")
addAttachment(head, "FaceFrontAttachment", Vector3.new(0, 0, -0.6))
addAttachment(head, "HairAttachment", Vector3.new(0, 0.6, 0))
addAttachment(head, "HatAttachment", Vector3.new(0, 0.6, 0))
addAttachment(head, "NeckRigAttachment", Vector3.new(0, -0.5, 0))
return character, humanoid
end
local function createR15Package(packageAssetId)
local packageAssetInfo = MarketplaceService:GetProductInfo(packageAssetId)
local character, humanoid = createBaseCharacter()
character.Name = packageAssetInfo.Name
local assetIds = AssetService:GetAssetIdsForPackage(packageAssetId)
for _, assetId in pairs(assetIds) do
local limb = InsertService:LoadAsset(assetId)
local r15 = limb:FindFirstChild("R15")
if r15 then
for _, part in pairs(r15:GetChildren()) do
part.Parent = character
end
else
for _, child in pairs(limb:GetChildren()) do
child.Parent = character
end
end
end
humanoid:BuildRigFromAttachments()
return character
end
local r15Package = createR15Package(PACKAGE_ASSET_ID)
r15Package.Parent = workspace

ChangeState

void

This function causes the Humanoid to enter the given Enum.HumanoidStateType, describing the activity the Humanoid is currently doing.

Please review the Enum.HumanoidStateType page for more information on the particular states, as some have unintuitive names. For example, Enum.HumanoidStateType.Running describes a state where the humanoid's legs are on the ground, including when stationary.

Due to the default behavior of the Humanoid, some states will automatically be changed when set. For example:

See also Humanoid:SetStateEnabled() to enable or disable a particular state, and Humanoid:GetState() to get the current humanoid state.

Parámetros

The Enum.HumanoidStateType that the Humanoid is to perform.

Valor predeterminado: "None"

Devuelve

void

Muestras de código

Double Jump

local UserInputService = game:GetService("UserInputService")
local character = script.Parent
local humanoid = character:WaitForChild("Humanoid")
local doubleJumpEnabled = false
humanoid.StateChanged:Connect(function(_oldState, newState)
if newState == Enum.HumanoidStateType.Jumping then
if not doubleJumpEnabled then
task.wait(0.2)
if humanoid:GetState() == Enum.HumanoidStateType.Freefall then
doubleJumpEnabled = true
end
end
elseif newState == Enum.HumanoidStateType.Landed then
doubleJumpEnabled = false
end
end)
UserInputService.InputBegan:Connect(function(inputObject)
if inputObject.KeyCode == Enum.KeyCode.Space then
if doubleJumpEnabled then
if humanoid:GetState() ~= Enum.HumanoidStateType.Jumping then
humanoid:ChangeState(Enum.HumanoidStateType.Jumping)
task.spawn(function()
doubleJumpEnabled = false
end)
end
end
end
end)

EquipTool

void

This function makes the Humanoid equip the given Tool.

The below example would cause a Player to equip a tool in Workspace named 'Tool'.


local Players = game:GetService("Players")
local player = Players:FindFirstChildOfClass("Player")
if player and player.Character then
local humanoid = player.Character:FindFirstChildWhichIsA("Humanoid")
if humanoid then
local tool = workspace:FindFirstChild("Tool")
if tool then
humanoid:EquipTool(tool)
end
end
end

When this function is called, the humanoid will automatically unequip any Tools that it currently has equipped

Although they will be equipped, Tools for which Tool.RequiresHandle is true will not function if they have no handle, regardless if this function is used to equip them or not

See also:

Parámetros

tool: Instance

The Tool to equip.


Devuelve

void

GetAccessories

This function returns an array of Accessory objects that the humanoid's parent is currently wearing. All such Accessory objects will be included, regardless of whether they're attached or not.

If the Humanoid has no Accessory objects, an empty array will be returned.

See also Humanoid:AddAccessory() to attach an Accessory to a humanoid's parent.


Devuelve

An array of Accessory objects that are parented to the humanoid's parent.

Muestras de código

Remove Accessories After Loading

local Players = game:GetService("Players")
local function onPlayerAddedAsync(player)
local connection = player.CharacterAppearanceLoaded:Connect(function(character)
-- All accessories have loaded at this point
local humanoid = character:FindFirstChildOfClass("Humanoid")
local numAccessories = #humanoid:GetAccessories()
print(("Destroying %d accessories for %s"):format(numAccessories, player.Name))
humanoid:RemoveAccessories()
end)
-- Make sure we disconnect our connection to the player after they leave
-- to allow the player to get garbage collected
player.AncestryChanged:Wait()
connection:Disconnect()
end
for _, player in Players:GetPlayers() do
task.spawn(onPlayerAddedAsync, player)
end
Players.PlayerAdded:Connect(onPlayerAddedAsync)

GetAppliedDescription

This function returns a copy of the humanoid's cached HumanoidDescription which describes its current look. This can be used to quickly determine a character's look and to assign their look to other characters using the Humanoid:ApplyDescription() function.

See Also


Devuelve

GetBodyPartR15

This function returns what Enum.BodyPartR15 a Part is, or Enum.BodyPartR15.Unknown if the part is not an R15 body part. This function allows developers to retrieve player body parts independent of what the actual body part names are, instead returning an enum.

It can be used in conjunction with Humanoid:ReplaceBodyPartR15(). For example, if a player's body part touches something, this function will return get a part instance. Developers can then look up what part of the body that was, like head or arm. Then depending on what that part was, developers can either perform some gameplay action or replace that part with some other part - perhaps showing damage.

This function can be useful for games where hit location is important. For example, it can be used to determine if a player is hit in the leg and then slow them down based on the injury.

Parámetros

part: Instance

The specified part being checked to see if it is an R15 body part.


Devuelve

The specified part's R15 body part type or unknown if the part is not a body part.

GetLimb

This function returns the Enum.Limb enum that is associated with the given Part. It works for both R15 and R6 rigs, for example:


-- For R15
print(humanoid:GetLimb(character.LeftUpperLeg)) -- Enum.Limb.LeftLeg
print(humanoid:GetLimb(character.LeftLowerLeg)) -- Enum.Limb.LeftLeg
print(humanoid:GetLimb(character.LeftFoot)) -- Enum.Limb.LeftLeg
-- For R6
print(humanoid:GetLimb(character:FindFirstChild("Left Leg"))) -- Enum.Limb.LeftLeg

Note that Humanoid:GetLimb() will throw an error if the part's parent is not set to the humanoid's parent.

Parámetros

part: Instance

The Part for which the Enum.Limb is to be retrieved.


Devuelve

The Enum.Limb the part corresponds with.

Muestras de código

Getting a Humanoid's Limbs

local Players = game:GetService("Players")
local player = Players.LocalPlayer
local character = player.Character or player.CharacterAdded:Wait()
local humanoid = character:WaitForChild("Humanoid")
for _, child in pairs(character:GetChildren()) do
local limb = humanoid:GetLimb(child)
if limb ~= Enum.Limb.Unknown then
print(child.Name .. " is part of limb " .. limb.Name)
end
end

GetMoveVelocity


Devuelve

Escribir paralelo

This function returns the humanoid's current Enum.HumanoidStateType, describing the activity the Humanoid is currently doing, such as jumping or swimming.

See also Humanoid:SetStateEnabled() to enable or disable a particular state, and Humanoid:ChangeState() to change the current humanoid state.


Devuelve

Muestras de código

Double Jump

local UserInputService = game:GetService("UserInputService")
local character = script.Parent
local humanoid = character:WaitForChild("Humanoid")
local doubleJumpEnabled = false
humanoid.StateChanged:Connect(function(_oldState, newState)
if newState == Enum.HumanoidStateType.Jumping then
if not doubleJumpEnabled then
task.wait(0.2)
if humanoid:GetState() == Enum.HumanoidStateType.Freefall then
doubleJumpEnabled = true
end
end
elseif newState == Enum.HumanoidStateType.Landed then
doubleJumpEnabled = false
end
end)
UserInputService.InputBegan:Connect(function(inputObject)
if inputObject.KeyCode == Enum.KeyCode.Space then
if doubleJumpEnabled then
if humanoid:GetState() ~= Enum.HumanoidStateType.Jumping then
humanoid:ChangeState(Enum.HumanoidStateType.Jumping)
task.spawn(function()
doubleJumpEnabled = false
end)
end
end
end
end)

GetStateEnabled

Escribir paralelo

The GetStateEnabled function returns whether a Enum.HumanoidStateType is enabled for the Humanoid.

The humanoid state describes the activity the humanoid is currently doing.

When a particular Enum.HumanoidStateType is disabled, the humanoid can never enter that state. This is true regardless if the attempt to change state is made using Humanoid:ChangeState() or Roblox internal humanoid code.

See also:

Parámetros


Devuelve

Whether the given Enum.HumanoidStateType is enabled.

Muestras de código

Setting and Getting Humanoid States

local humanoid = script.Parent:WaitForChild("Humanoid")
-- Set state
humanoid:SetStateEnabled(Enum.HumanoidStateType.Jumping, false)
-- Get state
print(humanoid:GetStateEnabled(Enum.HumanoidStateType.Jumping)) -- false

Move

void

This function causes the Humanoid to walk in the given Vector3 direction.

By default, the direction is in world terms, but If the relativeToCamera parameter is true, the direction is relative to the CFrame of the CurrentCamera. As the negative Z direction is considered "forwards" in Roblox, the following code will make the humanoid walk in the direction of the CurrentCamera.


humanoid:Move(Vector3.new(0, 0, -1), true)

When this function is called, the Humanoid will move until the function is called again. However, if the default control scripts are being used, this function will be overwritten when called on player Characters. This can be avoided by either not using the default control scripts, or calling this function every frame using RunService:BindToRenderStep() (see example).

This function can be called on the server, but this should only be done when the server has network ownership of the humanoid's assembly.

See also Humanoid:MoveTo() which makes aHumanoid walk to a point, and Player:Move() which effectively calls this function.

Parámetros

moveDirection: Vector3

The direction to walk in.

relativeToCamera: bool

Set to true if the moveDirection parameter should be taken as relative to the CurrentCamera.

Valor predeterminado: false

Devuelve

void

Muestras de código

Moving a Humanoid Forwards

local RunService = game:GetService("RunService")
local Players = game:GetService("Players")
local player = Players.LocalPlayer
RunService:BindToRenderStep("move", Enum.RenderPriority.Character.Value + 1, function()
if player.Character then
local humanoid = player.Character:FindFirstChild("Humanoid")
if humanoid then
humanoid:Move(Vector3.new(0, 0, -1), true)
end
end
end)

MoveTo

void

This function causes the Humanoid to attempt to walk to the given location by setting the Humanoid.WalkToPoint and Humanoid.WalkToPart properties.

The location and part parameters correspond with what Humanoid.WalkToPoint and Humanoid.WalkToPart will be set to.

If the part parameter is specified, the Humanoid will still attempt to walk to the point. However, if the part moves then the point the Humanoid is walking to will move to be at the same position relative to the part. If the part parameter is not specified, then the position the Humanoid is walking to will not change.

The reach goal state of a humanoid will timeout after 8 seconds if it doesn't reach its goal. This is done so that NPCs won't get stuck waiting for Humanoid.MoveToFinished to fire. If you don't want this to happen, you should repeatedly call MoveTo so that the timeout will keep resetting.

MoveTo() ends if any of the following conditions apply:

Parámetros

location: Vector3

The position to set Humanoid.WalkToPoint to.

part: Instance
Valor predeterminado: "nil"

Devuelve

void

Muestras de código

Humanoid MoveTo Without Time out

local function moveTo(humanoid, targetPoint, andThen)
local targetReached = false
-- listen for the humanoid reaching its target
local connection
connection = humanoid.MoveToFinished:Connect(function(reached)
targetReached = true
connection:Disconnect()
connection = nil
if andThen then
andThen(reached)
end
end)
-- start walking
humanoid:MoveTo(targetPoint)
-- execute on a new thread so as to not yield function
task.spawn(function()
while not targetReached do
-- does the humanoid still exist?
if not (humanoid and humanoid.Parent) then
break
end
-- has the target changed?
if humanoid.WalkToPoint ~= targetPoint then
break
end
-- refresh the timeout
humanoid:MoveTo(targetPoint)
task.wait(6)
end
-- disconnect the connection if it is still connected
if connection then
connection:Disconnect()
connection = nil
end
end)
end
local function andThen(reached)
print((reached and "Destination reached!") or "Failed to reach destination!")
end
moveTo(script.Parent:WaitForChild("Humanoid"), Vector3.new(50, 0, 50), andThen)

RemoveAccessories

void

This function removes all Accessory objects worn by the humanoid's parent. For player Characters, this will remove all hats and other accessories.

This function removes Accessory object by calling Instance:Destroy() on them, meaning the Parent of the accessories are set to nil and locked.

See also Humanoid:AddAccessory() to attach an Accessory, and Humanoid:GetAccessories() to get all Accessory objects belonging to a Humanoid.


Devuelve

void

Muestras de código

Remove Accessories After Loading

local Players = game:GetService("Players")
local function onPlayerAddedAsync(player)
local connection = player.CharacterAppearanceLoaded:Connect(function(character)
-- All accessories have loaded at this point
local humanoid = character:FindFirstChildOfClass("Humanoid")
local numAccessories = #humanoid:GetAccessories()
print(("Destroying %d accessories for %s"):format(numAccessories, player.Name))
humanoid:RemoveAccessories()
end)
-- Make sure we disconnect our connection to the player after they leave
-- to allow the player to get garbage collected
player.AncestryChanged:Wait()
connection:Disconnect()
end
for _, player in Players:GetPlayers() do
task.spawn(onPlayerAddedAsync, player)
end
Players.PlayerAdded:Connect(onPlayerAddedAsync)

ReplaceBodyPartR15

Dynamically replaces a R15/Rthro limb part in a Humanoid with a different part. The part is automatically scaled as normal.

This function is useful for modifying characters during gameplay or building characters from a base rig. The related function GetBodyPartR15 can come in handy when using this function.

The name of the part passed in should match with the name of the BodyPartR15 Enum passed in.

Parámetros

The body part to replace. Enum.BodyPartR15.Unknown will fail.

part: BasePart

The Part Instance which will be parented to the character.


Devuelve

SetStateEnabled

void

This function sets whether a given Enum.HumanoidStateType is enabled for the Humanoid. When a particular Enum.HumanoidStateType is disabled, the Humanoid can never enter that state. This is true regardless if the attempt to change state is made using Humanoid:ChangeState() or Roblox internal Humanoid code.

Note that using SetStateEnabled() on the server does not replicate the change to the client, nor vice-versa.

Parámetros

The Enum.HumanoidStateType to be enabled or disabled.

enabled: bool

true if state is to be enabled, false if state is to be disabled.


Devuelve

void

Muestras de código

Jump Cooldown

local character = script.Parent
local JUMP_DEBOUNCE = 1
local humanoid = character:WaitForChild("Humanoid")
local isJumping = false
humanoid.StateChanged:Connect(function(_oldState, newState)
if newState == Enum.HumanoidStateType.Jumping then
if not isJumping then
isJumping = true
humanoid:SetStateEnabled(Enum.HumanoidStateType.Jumping, false)
end
elseif newState == Enum.HumanoidStateType.Landed then
if isJumping then
isJumping = false
task.wait(JUMP_DEBOUNCE)
humanoid:SetStateEnabled(Enum.HumanoidStateType.Jumping, true)
end
end
end)

TakeDamage

void

This function lowers the Humanoid.Health of the Humanoid by the given amount if it is not protected by a ForceField

This function accepts negative values for the amount parameter. This will increase the humanoid's Humanoid.Health. However this will only have an effect if no ForceField is present.

How do ForceFields protect against TakeDamage

A Humanoid is considered protected by a ForceField if a ForceField meets one of the following criteria:

To do damage to a Humanoid irrespective of any ForceFields present, set Humanoid.Health directly.

For more information on how ForceFields protect Humanoids see the ForceField page

Parámetros

amount: number

The damage, or amount to be deduced from the Humanoid.Health.


Devuelve

void

Muestras de código

Damaging a Humanoid

local Players = game:GetService("Players")
local player = Players.LocalPlayer
local character = player.Character or player.CharacterAdded:Wait()
local humanoid = character:WaitForChild("Humanoid")
humanoid:TakeDamage(99)

UnequipTools

void

This function unequips any Tool currently equipped by the Humanoid

The unequipped Tool will be parented to the Backpack of the Player associated with the Humanoid.

If no Tool is equipped, this function will do nothing.

Although Tools can be equipped by NPCs (Non Player Characters), this function only works on Humanoids with a corresponding Player. This is because a Backpack object is required to parent the unequipped Tool to.

See also:


Devuelve

void

Muestras de código

Unequip Tool Keybind

local Players = game:GetService("Players")
local ContextActionService = game:GetService("ContextActionService")
local player = Players.LocalPlayer
ContextActionService:BindAction("unequipTools", function(_, userInputState)
if userInputState == Enum.UserInputState.Begin then
if player.Character then
local humanoid = player.Character:FindFirstChildOfClass("Humanoid")
if humanoid then
humanoid:UnequipTools()
end
end
end
end, false, Enum.KeyCode.U)

ApplyDescription

void
Proporciona

This yielding function makes the character's look match that of the passed in HumanoidDescription. A copy of the passed HumanoidDescription is cached as the HumanoidDescription for the Humanoid.

This function is optimized through making the assumption that only this function is used to change the appearance of the character, and no changes are made through other means between calls. If changes are made to the character between calls. Then this function may not make the character reflect the passed in HumanoidDescription accurately. If you want to use this function in conjunction with other means of updating the character, Humanoid:ApplyDescriptionReset() will always ensure the character reflects the passed in HumanoidDescription.

See Also

Parámetros

humanoidDescription: HumanoidDescription

The HumanoidDescription Instance which you want to set the character to match.

assetTypeVerification: Enum.AssetTypeVerification
Valor predeterminado: "Default"

Devuelve

void

ApplyDescriptionReset

void
Proporciona

This yielding function makes the character's look match that of the passed in HumanoidDescription, even after external changes. A copy of the passed HumanoidDescription is cached as the HumanoidDescription for the Humanoid.

This function will always ensure the character reflects the passed in HumanoidDescription, even if changes have been made to the character not using the HumanoidDescription system (for example not using ApplyDescriptionReset() or ApplyDescription()). This is in contrast to ApplyDescription() which is optimized and may incorrectly apply a HumanoidDescription if the character has been changed by means other than through the HumanoidDescription system.

Parámetros

humanoidDescription: HumanoidDescription

The HumanoidDescription instance which you want to set the character to match.

assetTypeVerification: Enum.AssetTypeVerification
Valor predeterminado: "Default"

Devuelve

void

PlayEmote

Proporciona

If the emote could not be played because the emoteName is not found in the HumanoidDescription this API will give an error. The API will return true to indicate that the emote was played successfully.

Parámetros

emoteName: string

name of the emote to play.


Devuelve

successfully played.

Eventos

ApplyDescriptionFinished

Parámetros

description: HumanoidDescription

Climbing

Fires when the speed at which a Humanoid is climbing changes.

Humanoids can climb up ladders made out of Parts or TrussParts.

Humanoids climb at 70% of their Humanoid.WalkSpeed.

This event will not always fire with a speed of 0 when the Humanoid stops climbing.

See also:

Parámetros

speed: number

The speed at which the Humanoid is currently climbing.


Muestras de código

Humanoid.Climbing

local Players = game:GetService("Players")
local function onCharacterClimbing(character, speed)
print(character.Name, "is climbing at a speed of", speed, "studs / second.")
end
local function onCharacterAdded(character)
character.Humanoid.Climbing:Connect(function(speed)
onCharacterClimbing(character, speed)
end)
end
local function onPlayerAdded(player)
player.CharacterAdded:Connect(onCharacterAdded)
end
Players.PlayerAdded:Connect(onPlayerAdded)

Died

This event fires when the Humanoid dies, usually when Humanoid.Health reaches 0. This could be caused either by disconnecting their head from their Humanoid.Torso, or directly setting the health property.

This event only fires if the Humanoid is a descendant of the Workspace. If the Dead Enum.HumanoidStateType is disabled it will not fire.


Muestras de código

Humanoid.Died

local Players = game:GetService("Players")
local function onPlayerAdded(player)
local function onCharacterAdded(character)
local humanoid = character:WaitForChild("Humanoid")
local function onDied()
print(player.Name, "has died!")
end
humanoid.Died:Connect(onDied)
end
player.CharacterAdded:Connect(onCharacterAdded)
end
Players.PlayerAdded:Connect(onPlayerAdded)

FallingDown

The FallingDown event fires when the Humanoid enters and leaves the FallingDown Enum.HumanoidStateType.

The Humanoid will enter the GettingUp state 3 seconds after the FallingDown state is enabled. When this happens this event will fire with an active value of false, and Humanoid.GettingUp will fire with an active value of true.

Parámetros

active: bool

Describes whether the Humanoid is entering or leaving the FallingDown Enum.HumanoidStateType.


FreeFalling

This event fires when the Humanoid enters or leaves the Freefall Enum.HumanoidStateType.

The active parameter represents whether the Humanoid is entering or leaving the Freefall state.

Although the Freefall state generally ends when the Humanoid reaches the ground, this event may fire with active equal to false if the state is changed while the Humanoid is falling. For this reason, you should use Humanoid.StateChanged and listen for the Landed state to work out when a Humanoid has landed.

Parámetros

active: bool

Whether the Humanoid is entering or leaving the Freefall Enum.HumanoidStateType.


GettingUp

This event fires when the Humanoid enters or leaves the Enum.HumanoidStateType.GettingUp state, a transition state that is activated shortly after the Humanoid enters the FallingDown (3 seconds) or Ragdoll (1 second) states.

When a Humanoid attempts to get back up, this event will first fire with an active parameter of true before shortly after firing again with an active parameter of false.

To force a Humanoid to fall over, use the Humanoid:ChangeState() function with Enum.HumanoidStateType.FallingDown.

Parámetros

active: bool

Whether the Humanoid is entering or leaving the GettingUp Enum.HumanoidStateType.


HealthChanged

This event fires when the Humanoid.Health changes. However, it will not fire if the health is increasing from a value equal to or greater than the Humanoid.MaxHealth.

When Humanoid.Health reaches zero, the Humanoid will die and the Humanoid.Died event will fire. This event will fire with a value of zero.

Parámetros

health: number

The new value of Humanoid.Health.


Muestras de código

Humanoid.HealthChanged

local Players = game:GetService("Players")
local player = Players.LocalPlayer
local function onCharacterAdded(character)
local humanoid = character:WaitForChild("Humanoid")
local currentHealth = humanoid.Health
local function onHealthChanged(health)
local change = math.abs(currentHealth - health)
print("The humanoid's health", (currentHealth > health and "decreased by" or "increased by"), change)
currentHealth = health
end
humanoid.HealthChanged:Connect(onHealthChanged)
end
player.CharacterAdded:Connect(onCharacterAdded)
Health Bar

local Players = game:GetService("Players")
local player = Players.LocalPlayer
-- Paste script into a LocalScript that is
-- parented to a Frame within a Frame
local frame = script.Parent
local container = frame.Parent
container.BackgroundColor3 = Color3.new(0, 0, 0) -- black
-- This function is called when the humanoid's health changes
local function onHealthChanged()
local human = player.Character.Humanoid
local percent = human.Health / human.MaxHealth
-- Change the size of the inner bar
frame.Size = UDim2.new(percent, 0, 1, 0)
-- Change the color of the health bar
if percent < 0.1 then
frame.BackgroundColor3 = Color3.new(1, 0, 0) -- black
elseif percent < 0.4 then
frame.BackgroundColor3 = Color3.new(1, 1, 0) -- yellow
else
frame.BackgroundColor3 = Color3.new(0, 1, 0) -- green
end
end
-- This function runs is called the player spawns in
local function onCharacterAdded(character)
local human = character:WaitForChild("Humanoid")
-- Pattern: update once now, then any time the health changes
human.HealthChanged:Connect(onHealthChanged)
onHealthChanged()
end
-- Connect our spawn listener; call it if already spawned
player.CharacterAdded:Connect(onCharacterAdded)
if player.Character then
onCharacterAdded(player.Character)
end

Jumping

This event fires when the Humanoid enters and leaves the Jumping Enum.HumanoidStateType.

When a Humanoid jumps, this event fires with an active parameter of true before shortly afterwards firing again with an active parameter of false. This second firing does not correspond with a Humanoid landing; for that, listen for the Landed Enum.HumanoidStateType using Humanoid.StateChanged.

You can disable jumping using the Humanoid:SetStateEnabled() function.

Parámetros

active: bool

Whether the Humanoid is entering or leaving the Jumping Enum.HumanoidStateType.


MoveToFinished

This event fires when the Humanoid finishes walking to a goal declared by the Humanoid.WalkToPoint and Humanoid.WalkToPart properties.

The Humanoid.WalkToPoint and Humanoid.WalkToPart properties can be set individually, or using the Humanoid:MoveTo() function.

If the Humanoid reaches its goal within 8 seconds, this event will return with reached as true. If the goal is not reached within 8 seconds the Humanoid will stop walking and reached will be false. This timeout can be reset be calling Humanoid:MoveTo() again within the timeout period.

Parámetros

reached: bool

A boolean indicating whether the Humanoid reached is goal. True if the Humanoid is reached its goal, false if the walk timed out before the goal could be reached.


Muestras de código

Humanoid MoveTo Without Time out

local function moveTo(humanoid, targetPoint, andThen)
local targetReached = false
-- listen for the humanoid reaching its target
local connection
connection = humanoid.MoveToFinished:Connect(function(reached)
targetReached = true
connection:Disconnect()
connection = nil
if andThen then
andThen(reached)
end
end)
-- start walking
humanoid:MoveTo(targetPoint)