Classe de moteur
BasePart
*Ce contenu est traduit en utilisant l'IA (Beta) et peut contenir des erreurs. Pour consulter cette page en anglais, clique ici.
Résumé
Propriétés
Méthodes
Événements
StoppedTouching(otherPart: BasePart):RBXScriptSignal |
Touched(otherPart: BasePart):RBXScriptSignal |
TouchEnded(otherPart: BasePart):RBXScriptSignal |
Hérité par
Échantillons de code
Lissage du CFrame d'une Partie
local TweenService = game:GetService("TweenService")
-- créer une partie et une cible
local part = Instance.new("Part", workspace)
part.Size = Vector3.one
part.Anchored = true
part.BrickColor = BrickColor.new("Electric blue")
part.CFrame = CFrame.new(0, 4, 0)
local target = Instance.new("Part", workspace)
target.Name = "Target"
target.Size = Vector3.one * 0.5
target.Anchored = true
target.BrickColor = BrickColor.new("Really red")
target.CFrame = CFrame.new(0, 8, 0)
-- configurer une variable pour stocker la vitesse
local velocity = CFrame.new()
-- ajuster la vitesse de lissage
local smoothTime = 0.5
game:GetService("RunService").Stepped:Connect(function(t, dt)
part.CFrame, velocity = TweenService:SmoothDamp(part.CFrame, target.CFrame, velocity, smoothTime, math.huge, dt)
end)Référence API
Propriétés
Anchored
Échantillons de code
Activation du Part Ancré
local part = script.Parent
-- Créez un ClickDetector pour savoir quand la pièce est cliquée
local cd = Instance.new("ClickDetector", part)
-- Cette fonction met à jour l'apparence de la pièce en fonction de son état Ancré
local function updateVisuals()
if part.Anchored then
-- Lorsque la pièce est ancrée...
part.BrickColor = BrickColor.new("Rouge vif")
part.Material = Enum.Material.DiamondPlate
else
-- Lorsque la pièce n'est pas ancrée...
part.BrickColor = BrickColor.new("Jaune vif")
part.Material = Enum.Material.Wood
end
end
local function onToggle()
-- Bascule la propriété ancrée
part.Anchored = not part.Anchored
-- Met à jour l'état visuel de la brique
updateVisuals()
end
-- Met à jour, puis commence à écouter les clics
updateVisuals()
cd.MouseClick:Connect(onToggle)BackParamA
BackParamB
BackSurfaceInput
BottomParamA
BottomParamB
BottomSurfaceInput
brickColor
CanCollide
Échantillons de code
Porte Floue
-- Collez dans un Script à l'intérieur d'une pièce haute
local part = script.Parent
local OPEN_TIME = 1
-- La porte peut-elle être ouverte en ce moment?
local debounce = false
local function open()
part.CanCollide = false
part.Transparency = 0.7
part.BrickColor = BrickColor.new("Noir")
end
local function close()
part.CanCollide = true
part.Transparency = 0
part.BrickColor = BrickColor.new("Bleu vif")
end
local function onTouch(otherPart)
-- Si la porte était déjà ouverte, ne rien faire
if debounce then
print("D")
return
end
-- Vérifiez si touché par un Humanoïde
local human = otherPart.Parent:FindFirstChildOfClass("Humanoid")
if not human then
print("pas humain")
return
end
-- Effectuer la séquence d'ouverture de la porte
debounce = true
open()
task.wait(OPEN_TIME)
close()
debounce = false
end
part.Touched:Connect(onTouch)
close()CFrame
Échantillons de code
Définir le CFrame de la pièce
local part = script.Parent:WaitForChild("Part")
local otherPart = script.Parent:WaitForChild("OtherPart")
-- Réinitialiser le CFrame de la pièce à (0, 0, 0) sans rotation.
-- Cela s'appelle parfois le "CFrame d'identité"
part.CFrame = CFrame.new()
-- Définir à une position spécifique (X, Y, Z)
part.CFrame = CFrame.new(0, 25, 10)
-- Même chose que ci-dessus, mais utiliser un Vector3 à la place
local point = Vector3.new(0, 25, 10)
part.CFrame = CFrame.new(point)
-- Définir le CFrame de la pièce pour être à un point, regardant un autre
local lookAtPoint = Vector3.new(0, 20, 15)
part.CFrame = CFrame.lookAt(point, lookAtPoint)
-- Faire pivoter le CFrame de la pièce de pi/2 radians sur l'axe X local
part.CFrame = part.CFrame * CFrame.Angles(math.pi / 2, 0, 0)
-- Faire pivoter le CFrame de la pièce de 45 degrés sur l'axe Y local
part.CFrame = part.CFrame * CFrame.Angles(0, math.rad(45), 0)
-- Faire pivoter le CFrame de la pièce de 180 degrés sur l'axe Z global (notez l'ordre !)
part.CFrame = CFrame.Angles(0, 0, math.pi) * part.CFrame -- Pi radians équivalent à 180 degrés
-- Composer deux CFrames se fait en utilisant * (l'opérateur de multiplication)
part.CFrame = CFrame.new(2, 3, 4) * CFrame.new(4, 5, 6) --> équivalent à CFrame.new(6, 8, 10)
-- Contrairement à la multiplication algébrique, la composition CFrame n'est PAS commutative : a * b n'est pas nécessairement b * a !
-- Imaginez * comme une série d'actions ORDONNÉE. Par exemple, les lignes suivantes produisent des CFrames différents :
-- 1) Glisser la pièce de 5 unités sur X.
-- 2) Faire pivoter la pièce de 45 degrés autour de son axe Y.
part.CFrame = CFrame.new(5, 0, 0) * CFrame.Angles(0, math.rad(45), 0)
-- 1) Faire pivoter la pièce de 45 degrés autour de son axe Y.
-- 2) Glisser la pièce de 5 unités sur X.
part.CFrame = CFrame.Angles(0, math.rad(45), 0) * CFrame.new(5, 0, 0)
-- Il n'y a pas de "division CFrame", mais simplement "faire l'opération inverse".
part.CFrame = CFrame.new(4, 5, 6) * CFrame.new(4, 5, 6):Inverse() --> équivalent à CFrame.new(0, 0, 0)
part.CFrame = CFrame.Angles(0, 0, math.pi) * CFrame.Angles(0, 0, math.pi):Inverse() --> équivalent à CFrame.Angles(0, 0, 0)
-- Positionner une pièce par rapport à une autre (dans ce cas, placer notre pièce au-dessus de otherPart)
part.CFrame = otherPart.CFrame * CFrame.new(0, part.Size.Y / 2 + otherPart.Size.Y / 2, 0)CollisionGroup
Échantillons de code
PhysicsService:RegisterCollisionGroup
local PhysicsService = game:GetService("PhysicsService")
local collisionGroupBall = "CollisionGroupBall"
local collisionGroupDoor = "CollisionGroupDoor"
-- Enregistrer les groupes de collision
PhysicsService:RegisterCollisionGroup(collisionGroupBall)
PhysicsService:RegisterCollisionGroup(collisionGroupDoor)
-- Assigner les parties aux groupes de collision
script.Parent.BallPart.CollisionGroup = collisionGroupBall
script.Parent.DoorPart.CollisionGroup = collisionGroupDoor
-- Définir les groupes comme non-collidables entre eux et vérifier le résultat
PhysicsService:CollisionGroupSetCollidable(collisionGroupBall, collisionGroupDoor, false)
print(PhysicsService:CollisionGroupsAreCollidable(collisionGroupBall, collisionGroupDoor)) --> falseCollisionGroupId
Color
Échantillons de code
Couleur du corps de santé du personnage
-- Collez dans un Script dans StarterCharacterScripts
-- Ensuite, jouez au jeu et ajustez la santé de votre personnage
local char = script.Parent
local human = char.Humanoid
local colorHealthy = Color3.new(0.4, 1, 0.2)
local colorUnhealthy = Color3.new(1, 0.4, 0.2)
local function setColor(color)
for _, child in pairs(char:GetChildren()) do
if child:IsA("BasePart") then
child.Color = color
while child:FindFirstChildOfClass("Decal") do
child:FindFirstChildOfClass("Decal"):Destroy()
end
elseif child:IsA("Accessory") then
child.Handle.Color = color
local mesh = child.Handle:FindFirstChildOfClass("SpecialMesh")
if mesh then
mesh.TextureId = ""
end
elseif child:IsA("Shirt") or child:IsA("Pants") then
child:Destroy()
end
end
end
local function update()
local percentage = human.Health / human.MaxHealth
-- Crée une couleur en fonction du pourcentage de votre santé
-- La couleur passe de colorHealthy (100%) ----- > colorUnhealthy (0%)
local color = Color3.new(
colorHealthy.R * percentage + colorUnhealthy.r * (1 - percentage),
colorHealthy.G * percentage + colorUnhealthy.g * (1 - percentage),
colorHealthy.B * percentage + colorUnhealthy.b * (1 - percentage)
)
setColor(color)
end
update()
human.HealthChanged:Connect(update)CustomPhysicalProperties
Échantillons de code
Définir CustomPhysicalProperties
local part = script.Parent
-- Cela rendra la pièce légère et rebondissante !
local DENSITY = 0.3
local FRICTION = 0.1
local ELASTICITY = 1
local FRICTION_WEIGHT = 1
local ELASTICITY_WEIGHT = 1
local physProperties = PhysicalProperties.new(DENSITY, FRICTION, ELASTICITY, FRICTION_WEIGHT, ELASTICITY_WEIGHT)
part.CustomPhysicalProperties = physPropertiesElasticity
Friction
FrontParamA
FrontParamB
FrontSurfaceInput
LeftParamA
LeftParamB
LeftSurfaceInput
Locked
Échantillons de code
Déverrouillage Récursif
-- Collez dans un script à l'intérieur d'un modèle que vous souhaitez déverrouiller
local model = script.Parent
-- Cette fonction parcourt récursivement l'héritage d'un modèle et déverrouille
-- chaque partie qu'elle rencontre.
local function recursiveUnlock(object)
if object:IsA("BasePart") then
object.Locked = false
end
-- Appelez la même fonction sur les enfants de l'objet
-- Le processus récursif s'arrête si un objet n'a pas d'enfants
for _, child in pairs(object:GetChildren()) do
recursiveUnlock(child)
end
end
recursiveUnlock(model)Orientation
Échantillons de code
Tourne-Parts
local part = script.Parent
local INCREMENT = 360 / 20
-- Faire tourner la pièce en continu
while true do
for degrees = 0, 360, INCREMENT do
-- Définir uniquement la rotation de l'axe Y
part.Rotation = Vector3.new(0, degrees, 0)
-- Une meilleure façon de faire cela serait de définir CFrame
--part.CFrame = CFrame.new(part.Position) * CFrame.Angles(0, math.rad(degrees), 0)
task.wait()
end
endPivotOffset
Échantillons de code
Réinitialiser le pivot
local function resetPivot(model)
local boundsCFrame = model:GetBoundingBox()
if model.PrimaryPart then
model.PrimaryPart.PivotOffset = model.PrimaryPart.CFrame:ToObjectSpace(boundsCFrame)
else
model.WorldPivot = boundsCFrame
end
end
resetPivot(script.Parent)Aiguilles de l'horloge
local function createHand(length, width, yOffset)
local part = Instance.new("Part")
part.Size = Vector3.new(width, 0.1, length)
part.Material = Enum.Material.Neon
part.PivotOffset = CFrame.new(0, -(yOffset + 0.1), length / 2)
part.Anchored = true
part.Parent = workspace
return part
end
local function positionHand(hand, fraction)
hand:PivotTo(CFrame.fromEulerAnglesXYZ(0, -fraction * 2 * math.pi, 0))
end
-- Créer le cadran
for i = 0, 11 do
local dialPart = Instance.new("Part")
dialPart.Size = Vector3.new(0.2, 0.2, 1)
dialPart.TopSurface = Enum.SurfaceType.Smooth
if i == 0 then
dialPart.Size = Vector3.new(0.2, 0.2, 2)
dialPart.Color = Color3.new(1, 0, 0)
end
dialPart.PivotOffset = CFrame.new(0, -0.1, 10.5)
dialPart.Anchored = true
dialPart:PivotTo(CFrame.fromEulerAnglesXYZ(0, (i / 12) * 2 * math.pi, 0))
dialPart.Parent = workspace
end
-- Créer les aiguilles
local hourHand = createHand(7, 1, 0)
local minuteHand = createHand(10, 0.6, 0.1)
local secondHand = createHand(11, 0.2, 0.2)
-- Exécuter l'horloge
while true do
local components = os.date("*t")
positionHand(hourHand, (components.hour + components.min / 60) / 12)
positionHand(minuteHand, (components.min + components.sec / 60) / 60)
positionHand(secondHand, components.sec / 60)
task.wait()
endResizeableFaces
Échantillons de code
Poignées de redimensionnement
-- Placez ce script dans plusieurs types de BasePart, comme
-- Part, TrussPart, WedgePart, CornerWedgePart, etc.
local part = script.Parent
-- Créer un objet handles pour cette pièce
local handles = Instance.new("Handles")
handles.Adornee = part
handles.Parent = part
-- Spécifiez manuellement les faces applicables pour cette poignée
handles.Faces = Faces.new(Enum.NormalId.Top, Enum.NormalId.Front, Enum.NormalId.Left)
-- Alternativement, utilisez les faces sur lesquelles la pièce peut être redimensionnée.
-- Si la pièce est un TrussPart avec seulement deux dimensions de taille
-- de longueur 2, alors ResizeableFaces n'aura que deux
-- faces activées. Pour d'autres pièces, toutes les faces seront activées.
handles.Faces = part.ResizeableFacesRightParamA
RightParamB
RightSurfaceInput
RotVelocity
Size
Échantillons de code
Constructeur de pyramides
local TOWER_BASE_SIZE = 30
local position = Vector3.new(50, 50, 50)
local hue = math.random()
local color0 = Color3.fromHSV(hue, 1, 1)
local color1 = Color3.fromHSV((hue + 0.35) % 1, 1, 1)
local model = Instance.new("Model")
model.Name = "Tour"
for i = TOWER_BASE_SIZE, 1, -2 do
local part = Instance.new("Part")
part.Size = Vector3.new(i, 2, i)
part.Position = position
part.Anchored = true
part.Parent = model
-- Transitionner de color0 à color1
local perc = i / TOWER_BASE_SIZE
part.Color = Color3.new(
color0.R * perc + color1.R * (1 - perc),
color0.G * perc + color1.G * (1 - perc),
color0.B * perc + color1.B * (1 - perc)
)
position = position + Vector3.new(0, part.Size.Y, 0)
end
model.Parent = workspaceSpecificGravity
TopParamA
TopParamB
TopSurfaceInput
Transparency
Échantillons de code
Porte Floue
-- Collez dans un Script à l'intérieur d'une pièce haute
local part = script.Parent
local OPEN_TIME = 1
-- La porte peut-elle être ouverte en ce moment?
local debounce = false
local function open()
part.CanCollide = false
part.Transparency = 0.7
part.BrickColor = BrickColor.new("Noir")
end
local function close()
part.CanCollide = true
part.Transparency = 0
part.BrickColor = BrickColor.new("Bleu vif")
end
local function onTouch(otherPart)
-- Si la porte était déjà ouverte, ne rien faire
if debounce then
print("D")
return
end
-- Vérifiez si touché par un Humanoïde
local human = otherPart.Parent:FindFirstChildOfClass("Humanoid")
if not human then
print("pas humain")
return
end
-- Effectuer la séquence d'ouverture de la porte
debounce = true
open()
task.wait(OPEN_TIME)
close()
debounce = false
end
part.Touched:Connect(onTouch)
close()Velocity
Méthodes
AngularAccelerationToTorque
ApplyAngularImpulse
ApplyImpulseAtPosition
BreakJoints
breakJoints
CanSetNetworkOwnership
Retours
Échantillons de code
Vérifiez si la propriété Network Ownership d'une partie peut être définie
local part = workspace:FindFirstChild("Part")
if part and part:IsA("BasePart") then
local canSet, errorReason = part:CanSetNetworkOwnership()
if canSet then
print(part:GetFullName() .. " peut changer son Network Ownership !")
else
warn("Impossible de modifier le Network Ownership de " .. part:GetFullName() .. " parce que: " .. errorReason)
end
endGetClosestPointOnSurface
GetConnectedParts
GetJoints
BasePart:GetJoints():Instances
Retours
Instances
GetMass
getMass
GetNoCollisionConstraints
BasePart:GetNoCollisionConstraints():Instances
Retours
Instances
GetRenderCFrame
GetRootPart
GetTouchingParts
BasePart:GetTouchingParts():Instances
Retours
Instances
GetVelocityAtPosition
IntersectAsync
BasePart:IntersectAsync(
Paramètres
parts:Instances |
| Valeur par défaut : "Default" |
| Valeur par défaut : "Automatic" |
Retours
MakeJoints
makeJoints
Resize
Paramètres
Retours
resize
SetNetworkOwner
SetNetworkOwnershipAuto
BasePart:SetNetworkOwnershipAuto():()
Retours
()
SubtractAsync
BasePart:SubtractAsync(
Paramètres
parts:Instances |
| Valeur par défaut : "Default" |
| Valeur par défaut : "Automatic" |
Retours
Échantillons de code
BasePart:SubtractAsync()
local Workspace = game:GetService("Workspace")
local mainPart = script.Parent.PartA
local otherParts = { script.Parent.PartB, script.Parent.PartC }
-- Effectuer l'opération de soustraction
local success, newSubtract = pcall(function()
return mainPart:SubtractAsync(otherParts)
end)
-- Si l'opération réussit, positionner à la même location et le parenté au workspace
if success and newSubtract then
newSubtract.Position = mainPart.Position
newSubtract.Parent = Workspace
end
-- Détruire les pièces originales qui restent intactes après l'opération
mainPart:Destroy()
for _, part in otherParts do
part:Destroy()
endTorqueToAngularAcceleration
UnionAsync
BasePart:UnionAsync(
Paramètres
parts:Instances |
| Valeur par défaut : "Default" |
| Valeur par défaut : "Automatic" |
Retours
Échantillons de code
BasePart:UnionAsync()
local Workspace = game:GetService("Workspace")
local mainPart = script.Parent.PartA
local otherParts = { script.Parent.PartB, script.Parent.PartC }
-- Effectuer l'opération de union
local success, newUnion = pcall(function()
return mainPart:UnionAsync(otherParts)
end)
-- Si l'opération réussit, le positionner au même endroit et le parenté au workspace
if success and newUnion then
newUnion.Position = mainPart.Position
newUnion.Parent = Workspace
end
-- Détruire les pièces originales qui restent intactes après l'opération
mainPart:Destroy()
for _, part in otherParts do
part:Destroy()
endÉvénements
LocalSimulationTouched
OutfitChanged
StoppedTouching
Touched
Paramètres
Échantillons de code
Nombre de pièces touchées
local part = script.Parent
local billboardGui = Instance.new("BillboardGui")
billboardGui.Size = UDim2.new(0, 200, 0, 50)
billboardGui.Adornee = part
billboardGui.AlwaysOnTop = true
billboardGui.Parent = part
local tl = Instance.new("TextLabel")
tl.Size = UDim2.new(1, 0, 1, 0)
tl.BackgroundTransparency = 1
tl.Parent = billboardGui
local numTouchingParts = 0
local function onTouch(otherPart)
print("Début du contact: " .. otherPart.Name)
numTouchingParts = numTouchingParts + 1
tl.Text = numTouchingParts
end
local function onTouchEnded(otherPart)
print("Fin du contact: " .. otherPart.Name)
numTouchingParts = numTouchingParts - 1
tl.Text = numTouchingParts
end
part.Touched:Connect(onTouch)
part.TouchEnded:Connect(onTouchEnded)Modèle Touché
local model = script.Parent
local function onTouched(otherPart)
-- Ignorer les instances du modèle entrant en contact avec lui-même
if otherPart:IsDescendantOf(model) then
return
end
print(model.Name .. " a percuté " .. otherPart.Name)
end
for _, child in pairs(model:GetChildren()) do
if child:IsA("BasePart") then
child.Touched:Connect(onTouched)
end
endTouchEnded
Paramètres
Échantillons de code
Nombre de pièces touchées
local part = script.Parent
local billboardGui = Instance.new("BillboardGui")
billboardGui.Size = UDim2.new(0, 200, 0, 50)
billboardGui.Adornee = part
billboardGui.AlwaysOnTop = true
billboardGui.Parent = part
local tl = Instance.new("TextLabel")
tl.Size = UDim2.new(1, 0, 1, 0)
tl.BackgroundTransparency = 1
tl.Parent = billboardGui
local numTouchingParts = 0
local function onTouch(otherPart)
print("Début du contact: " .. otherPart.Name)
numTouchingParts = numTouchingParts + 1
tl.Text = numTouchingParts
end
local function onTouchEnded(otherPart)
print("Fin du contact: " .. otherPart.Name)
numTouchingParts = numTouchingParts - 1
tl.Text = numTouchingParts
end
part.Touched:Connect(onTouch)
part.TouchEnded:Connect(onTouchEnded)