Humanoid
*此內容很快就會推出您所選的語言版本。
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
範例程式碼
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)
概要
屬性
Sets whether the character will automatically jump when they hit an obstacle as a player on a mobile device.
AutoRotate sets whether or not the Humanoid will automatically rotate to face in the direction they are moving in.
When Enabled, AutomaticScalingEnabled causes the size of the character to change in response to the values in the humanoid's child scale values changing.
Determines whether the humanoid's joints break when in the Enum.HumanoidStateType.Dead state.
An offset applied to the Camera's subject position when its CameraSubject is set to this Humanoid.
Controls the distance behavior of the humanoid's name and health display.
Sets the text of a Humanoid, displayed above their head.
Describes the Enum.Material that the Humanoid is currently standing on. If the Humanoid isn't standing on anything, the value of this property will be Air.
Describes the current health of the Humanoid on the range [0, Humanoid.MaxHealth].
Used in conjunction with the DisplayDistanceType property to control the distance from which a humanoid's health bar can be seen.
Controls when the humanoid's health bar is allowed to be displayed.
Determines the distance off the ground the Humanoid.RootPart should be.
If true, the Humanoid jumps with an upwards force.
Provides control over the height that the Humanoid jumps to.
Determines how much upwards force is applied to the Humanoid when jumping.
The maximum value of a humanoid's Health.
The maximum slope angle that a humanoid can walk on without slipping.
Describes the direction that the Humanoid is walking in.
Used in conjunction with the Humanoid.DisplayDistanceType property to control the distance from which a humanoid's name can be seen.
Controls whether a humanoid's name and health bar can be seen behind walls or other objects.
Determines whether the Humanoid is currently in the Enum.HumanoidStateType.PlatformStanding state.
Allows developers to disable the behavior where a player Character|character dies if the Neck Motor6D is removed or disconnected even momentarily.
Describes whether this Humanoid is utilizing the legacy R6 character rig, or the new R15 character rig.
A reference to the humanoid's HumanoidRootPart object.
A reference to the seat that a Humanoid is currently sitting in, if any.
Describes whether the Humanoid is currently sitting.
Describes the 3D position where the Player controlling the Humanoid last clicked in the world while using a Tool.
Determines whether the JumpHeight (false) or Humanoid.JumpPower (true) property is used.
Describes the humanoid's maximum movement speed in studs per second.
A reference to a part whose position is trying to be reached by a humanoid.
The position that a humanoid is trying to reach, after a call to Humanoid:MoveTo() is made.
方法
Attaches the specified Accessory to the humanoid's parent.
Assembles a tree of Motor6D joints by attaching together Attachment objects in a humanoid's character.
Sets the Humanoid to enter the given Enum.HumanoidStateType.
Returns an array of Accessory objects that the humanoid's parent is currently wearing.
Returns a copy of the humanoid's cached HumanoidDescription which describes its current look.
Pass a body part to this function (the body part should be a sibling of Humanoid, and a child of a Model) to get the Enum.BodyPartR15 of the Part.
Returns the Enum.Limb enum that is associated with the given Part.
Returns the humanoid's current Enum.HumanoidStateType.
Returns whether a Enum.HumanoidStateType is enabled for the Humanoid.
Causes the Humanoid to walk in the given direction.
Causes the Humanoid to attempt to walk to the given location by setting the Humanoid.WalkToPoint and Humanoid.WalkToPart properties.
Removes all Accessory objects worn by the humanoid's parent.
Dynamically replaces a Humanoid body part with a different part.
Sets whether a given Enum.HumanoidStateType is enabled for the Humanoid.
Lowers the Humanoid.Health of the Humanoid by the given amount if it is not protected by a ForceField.
- ApplyDescription(humanoidDescription : HumanoidDescription,assetTypeVerification : Enum.AssetTypeVerification):void
Makes the character's look match that of the passed in HumanoidDescription.
- ApplyDescriptionReset(humanoidDescription : HumanoidDescription,assetTypeVerification : Enum.AssetTypeVerification):void
Makes the character's look match that of the passed in HumanoidDescription, even after external changes.
Plays emotes and returns if was successfully ran.
活動
Fires when the speed at which a Humanoid is climbing changes.
Fires when the Humanoid dies.
Fires when the Humanoid enters or leaves the FallingDown Enum.HumanoidStateType.
Fires when the Humanoid enters or leaves the Freefall Enum.HumanoidStateType.
Fires when the Humanoid enters or leaves the GettingUp Enum.HumanoidStateType.
Fires when the Humanoid.Health changes (or when the Humanoid.MaxHealth is set).
Fires when the Humanoid enters and leaves the Jumping Enum.HumanoidStateType.
Fires when the Humanoid finishes walking to a goal declared by Humanoid:MoveTo().
Fires when the Humanoid enters or leaves the PlatformStanding Enum.HumanoidStateType.
Fires when the Humanoid enters or leaves the Ragdoll Enum.HumanoidStateType.
Fires when the speed at which a Humanoid is running changes.
Fired when a Humanoid either sits in a Seat or VehicleSeat or gets up.
Fires when the state of the Humanoid is changed.
Fires when Humanoid:SetStateEnabled() is called on the Humanoid.
Fires when the Humanoid enters or leaves the StrafingNoPhysics Enum.HumanoidStateType.
Fires when the speed at which a Humanoid is swimming in Terrain water changes.
Fires when one of the humanoid's limbs come in contact with another BasePart.
屬性
AutoJumpEnabled
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.
範例程式碼
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
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:
RotationType | Behavior | Context |
---|---|---|
MovementRelative | ||
CameraRelative | Character 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. |
範例程式碼
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
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
Determines whether the humanoid's joints break when in the Enum.HumanoidStateType.Dead state. Defaults to true.
CameraOffset
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.
範例程式碼
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)
DisplayDistanceType
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.
範例程式碼
local humanoid = script.Parent
humanoid.DisplayDistanceType = Enum.HumanoidDisplayDistanceType.Viewer
humanoid.HealthDisplayDistance = 0
humanoid.NameDisplayDistance = 100
DisplayName
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
FloorMaterial
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.
- You cannot test if the Humanoid is swimming with this property. You should instead use its Humanoid:GetState() function.
Health
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
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.
HealthDisplayType
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
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
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
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
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
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
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.
範例程式碼
local player = game.Players.LocalPlayer
local char = player.CharacterAdded:wait()
local h = char:FindFirstChild("Humanoid")
h.MaxSlopeAngle = 30
MoveDirection
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.
範例程式碼
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
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
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.
範例程式碼
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
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
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.
RigType
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
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
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:
- For a bool describing if the Humanoid is currently sitting or not, see Humanoid.Sit
Sit
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:
- The Seat or VehicleSeat the Humanoid is sitting on can be obtained using the Humanoid.SeatPart property
- It is possible to detect when a Humanoid sits by connecting to the Humanoid.Seated event.
TargetPoint
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
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
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.
WalkToPart
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
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.
範例程式碼
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)
方法
AddAccessory
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.
參數
返回
範例程式碼
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
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.
返回
範例程式碼
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)
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
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:
- Setting the state to Enum.HumanoidStateType.Swimming when the humanoid is not in the water will cause it to be automatically set to Enum.HumanoidStateType.GettingUp.
- As it is unused, setting the state to Enum.HumanoidStateType.PlatformStanding will cause the humanoid state to be automatically set to Enum.HumanoidStateType.Running.
See also Humanoid:SetStateEnabled() to enable or disable a particular state, and Humanoid:GetState() to get the current humanoid state.
參數
The Enum.HumanoidStateType that the Humanoid is to perform.
返回
範例程式碼
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
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 thenlocal humanoid = player.Character:FindFirstChildWhichIsA("Humanoid")if humanoid thenlocal tool = workspace:FindFirstChild("Tool")if tool thenhumanoid:EquipTool(tool)endendend
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:
- To unequip tools, use Humanoid:UnequipTools()
參數
返回
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.
返回
範例程式碼
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
- Players:GetHumanoidDescriptionFromUserId() which returns a HumanoidDescription describing the avatar for the passed in user.
- Players:GetHumanoidDescriptionFromOutfitId() which returns a HumanoidDescription whose parameters are initialized to match that of the passed in server-side outfit asset.
- Player:LoadCharacterWithHumanoidDescription() which spawns a player with the look from the passed in HumanoidDescription.
返回
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.
參數
The specified part being checked to see if it is an R15 body part.
返回
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 R15print(humanoid:GetLimb(character.LeftUpperLeg)) -- Enum.Limb.LeftLegprint(humanoid:GetLimb(character.LeftLowerLeg)) -- Enum.Limb.LeftLegprint(humanoid:GetLimb(character.LeftFoot)) -- Enum.Limb.LeftLeg-- For R6print(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.
參數
返回
範例程式碼
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
GetState
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.
返回
The current Enum.HumanoidStateType of the Humanoid.
範例程式碼
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
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:
- For an event that fires when a humanoid state is enabled or disabled see Humanoid.StateEnabledChanged
- To enable or disable a Humanoid state use Humanoid:SetStateEnabled()
參數
The given Enum.HumanoidStateType.
返回
Whether the given Enum.HumanoidStateType is enabled.
範例程式碼
local humanoid = script.Parent:WaitForChild("Humanoid")
-- Set state
humanoid:SetStateEnabled(Enum.HumanoidStateType.Jumping, false)
-- Get state
print(humanoid:GetStateEnabled(Enum.HumanoidStateType.Jumping)) -- false
Move
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.
參數
The direction to walk in.
Set to true if the moveDirection parameter should be taken as relative to the CurrentCamera.
返回
範例程式碼
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
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:
The character arrives at its destination.
The character gets stuck and the eight-second timer expires.
The value of either Humanoid.WalkToPoint or Humanoid.WalkToPart changes.
A script calls Humanoid:Move() with a new moveDirection parameter.
參數
The position to set Humanoid.WalkToPoint to.
The BasePart to set Humanoid.WalkToPart to.
返回
範例程式碼
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
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.
返回
範例程式碼
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.
參數
The body part to replace. Enum.BodyPartR15.Unknown will fail.
返回
SetStateEnabled
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.
參數
The Enum.HumanoidStateType to be enabled or disabled.
true if state is to be enabled, false if state is to be disabled.
返回
範例程式碼
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
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
參數
The damage, or amount to be deduced from the Humanoid.Health.
返回
範例程式碼
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
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:
- To instead equip a Tool, use Humanoid:EquipTool()
返回
範例程式碼
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
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
- Humanoid:GetAppliedDescription() which returns the HumanoidDescription currently applied to the humanoid.
- Players:GetHumanoidDescriptionFromUserId() which returns a HumanoidDescription describing the avatar for the passed in user.
- Players:GetHumanoidDescriptionFromOutfitId() which returns a HumanoidDescription whose parameters are initialized to match that of the passed in server-side outfit asset.
- Player:LoadCharacterWithHumanoidDescription() which spawns a player with the look from the passed in HumanoidDescription.
參數
The HumanoidDescription Instance which you want to set the character to match.
返回
ApplyDescriptionReset
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.
參數
The HumanoidDescription instance which you want to set the character to match.
返回
活動
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:
- For swimming and running see the Humanoid.Swimming and Humanoid.Running events
- You can also detect when a Humanoid is climbing using the Humanoid.StateChanged event
- You can disable climbing using the Humanoid:SetStateEnabled() function
參數
範例程式碼
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.
範例程式碼
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.
參數
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.
參數
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.
參數
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.
參數
The new value of Humanoid.Health.
範例程式碼
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)
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.
參數
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.
參數
範例程式碼
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)
PlatformStanding
This event fires when the Humanoid enters or leaves the PlatformStanding Enum.HumanoidStateType.
Whilst the Humanoid is in the PlatformStanding state, the Humanoid.PlatformStand property will be true.
Whilst Humanoid.PlatformStand is set to true, the Humanoid will be unable to move. For more information please see the page for Humanoid.PlatformStand.
The PlatformStand Enum.HumanoidStateType was associated with the now disabled Platform part. Despite this, it can still be used by developers.
參數
Whether the Humanoid is entering or leaving the PlatformStanding Enum.HumanoidStateType.
Ragdoll
This event fires when the Humanoid enters or leaves the Ragdoll Enum.HumanoidStateType.
The active parameter will have the value true or false to indicate entering or leaving.
Use Humanoid:SetStateEnabled() to disable the GettingUp state to stay in the Ragdoll state.
See also:
- Humanoid.FallingDown for the Humanoid event connected with the FallingDown state, which behaves similarly to Ragdoll
參數
Whether the Humanoid is entering or leaving the Ragdoll Enum.HumanoidStateType.
Running
This event fires when the speed at which a Humanoid is running changes.
While running Humanoids cover, on average, their Humanoid.WalkSpeed in studs per second.
When the Humanoid stops running this event will fire with a speed of 0.
See also:
- For swimming and climbing see the Humanoid.Swimming and Humanoid.Climbing events
- You can also detect when a Humanoid is running using the Humanoid.StateChanged event
參數
範例程式碼
local Players = game:GetService("Players")
local localPlayer = Players.LocalPlayer
local character = localPlayer.Character or localPlayer.CharacterAdded:Wait()
local humanoid = character:WaitForChild("Humanoid")
local function onRunning(speed: number)
if speed > 0 then
print(`{localPlayer.Name} is running`)
else
print(`{localPlayer.Name} has stopped`)
end
end
humanoid.Running:Connect(function(speed: number)
onRunning(speed)
end)
Seated
This event fires when a Humanoid either sits in or gets up from a Seat or VehicleSeat.
When a character comes into contact with a seat, they are attached to the seat and a sitting animation plays. For more information on this, see the Seat page.
- If the character is sitting down, the active parameter will be true and currentSeatPart will be the seat they are currently sitting in.
- If the character got up from a seat, the active parameter will be false and currentSeatPart will be nil.
See also:
- Humanoid.Sit, which indicates if a Humanoid is currently sitting
- Humanoid.SeatPart, which indicates the seat a Humanoid is currently sitting in, if any.
參數
範例程式碼
local character = script.Parent
local humanoid = character:WaitForChild("Humanoid")
local function onSeated(isSeated, seat)
if isSeated then
print("I'm now sitting on: " .. seat.Name .. "!")
else
print("I'm not sitting on anything")
end
end
humanoid.Seated:Connect(onSeated)
StateChanged
This event fires when the state of the Humanoid is changed.
As there is no "idle" humanoid state, you should instead use the Humanoid.Running event or listen to the RootPart part's Velocity to work out when the Humanoid is standing still.
See Also
- Humanoid:GetState() and Humanoid:ChangeState() to get and set the state.
- Humanoid:SetStateEnabled() to enable and disable specific states.
參數
The humanoid's previous state type.
The humanoid's current state type.
範例程式碼
local character = script.Parent
local primaryPart = character.PrimaryPart
-- create particles
local particles = Instance.new("ParticleEmitter")
particles.Size = NumberSequence.new(1)
particles.Transparency = NumberSequence.new(0, 1)
particles.Acceleration = Vector3.new(0, -10, 0)
particles.Lifetime = NumberRange.new(1)
particles.Rate = 20
particles.EmissionDirection = Enum.NormalId.Back
particles.Enabled = false
particles.Parent = primaryPart
local humanoid = character:WaitForChild("Humanoid")
local isJumping = false
-- listen to humanoid state
local function onStateChanged(_oldState, newState)
if newState == Enum.HumanoidStateType.Jumping then
if not isJumping then
isJumping = true
particles.Enabled = true
end
elseif newState == Enum.HumanoidStateType.Landed then
if isJumping then
isJumping = false
particles.Enabled = false
end
end
end
humanoid.StateChanged:Connect(onStateChanged)
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)
StateEnabledChanged
The StateEnableChanged event fires when Humanoid:SetStateEnabled() is called on the Humanoid.
Parameters include the Enum.HumanoidStateType in question along with a bool indicating if this state is now enabled.
See also:
- To find if a state is currently enabled, use Humanoid:GetStateEnabled()
- To listen to Humanoid state changes use Humanoid.StateChanged
參數
The Enum.HumanoidStateType for which the enabled state has been changed.
True if the state is now enabled.
範例程式碼
local Players = game:GetService("Players")
local player = Players.LocalPlayer
local character = player.Character or player.CharacterAdded:Wait()
local humanoid = character:WaitForChild("Humanoid")
local function onStateEnabledChanged(state, enabled)
if enabled then
print(state.Name .. " has been enabled")
else
print(state.Name .. " has been disabled")
end
end
humanoid.StateEnabledChanged:Connect(onStateEnabledChanged)
Strafing
This event does not fire when the Humanoid is strafing and should not be used by developers
This event is fired when the Humanoid enters or leaves the StrafingNoPhysics Enum.HumanoidStateType.
When the Humanoid enters the StrafingNoPhysics state this event will fire with an active parameter of true. The event will fire again with active equal to false when the Humanoid leaves the StrafingNoPhysics state.
This event is associated with the StrafingNoPhysics Humanoid state and does not fire when the Humanoid is moving perpendicular to the direction it is facing. This state is currently unused, if it is set using Humanoid:ChangeState() the state will revert to RunningNoPhysics.
參數
Whether the Humanoid is entering or leaving the StrafingNoPhysics Enum.HumanoidStateType.
Swimming
This event fires when the speed at which a Humanoid is swimming in Terrain water changes.
Humanoids swim at 87.5% of their Humanoid.WalkSpeed.
This event will not always fire with a speed of 0 when the Humanoid stops swimming.
See also:
- For running and climbing see the Humanoid.Running and Humanoid.Climbing events
- You can also detect when a Humanoid is swimming using the Humanoid.StateChanged event
- You can disable swimming using the Humanoid:SetStateEnabled() function
參數
Touched
This event fires when one of the humanoid's limbs comes in contact with another BasePart. The BasePart which the limb is touching, along with the limb itself, is given.
This event will not fire when limbs belonging to the Humanoid come into contact with themselves.
Alternatives
Although the Humanoid.Touched event is useful, you should consider if there are alternatives that better suit your needs.
- In most cases, it's advised to connect a BasePart.Touched event for BaseParts of interest instead, as the Humanoid.Touched event will constantly fire when the humanoid is moving. For example, in a dodgeball game, it would be more practical to connect a Touched event for the balls rather than use Humanoid.Touched.
- When trying to work out when the Humanoid has landed on the ground, the Humanoid.StateChanged event is more suitable. Alternatively, you can check Humanoid.FloorMaterial to see if the humanoid is standing on any non-air material.
Notes
- Connecting to this event will cause a TouchTransmitter to be created in every limb.
- There is currently no equivalent of BasePart.TouchEnded for Humanoids.
參數
範例程式碼
local character = script.Parent
local humanoid = character:WaitForChild("Humanoid")
local partInfo = {}
local debounce = false
local function onHumanoidTouched(hit, _limb)
if debounce then
return
end
if not hit.CanCollide or hit.Transparency ~= 0 then
return
end
if not partInfo[hit] then
partInfo[hit] = {
BrickColor = hit.BrickColor,
Material = hit.Material,
}
hit.BrickColor = BrickColor.new("Gold")
hit.Material = Enum.Material.Ice
debounce = true
task.wait(0.2)
debounce = false
end
end
local touchedConnection = humanoid.Touched:Connect(onHumanoidTouched)
local function onHumanoidDied()
if touchedConnection then
touchedConnection:Disconnect()
end
-- undo all of the gold
for part, info in pairs(partInfo) do
if part and part.Parent then
part.BrickColor = info.BrickColor
part.Material = info.Material
end
end
end
humanoid.Died:Connect(onHumanoidDied)