요약
속성
메서드
이벤트
StoppedTouching(otherPart: BasePart):RBXScriptSignal |
Touched(otherPart: BasePart):RBXScriptSignal |
TouchEnded(otherPart: BasePart):RBXScriptSignal |
상속된 멤버
코드 샘플
부드러운 댐핑으로 부품의 CFrame 다루기
local TweenService = game:GetService("TweenService")
-- 부품과 목표를 생성합니다
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)
-- 속도를 저장할 변수를 설정합니다
local velocity = CFrame.new()
-- 부드러워지는 속도를 조정합니다
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)API 참조
속성
Anchored
코드 샘플
부품 고정 전환
local part = script.Parent
-- ClickDetector를 생성하여 부품이 클릭되었을 때 알림
local cd = Instance.new("ClickDetector", part)
-- 이 함수는 부품의 Anchored 상태에 따라 부품의 외관을 업데이트합니다
local function updateVisuals()
if part.Anchored then
-- 부품이 고정될 때...
part.BrickColor = BrickColor.new("밝은 빨강")
part.Material = Enum.Material.DiamondPlate
else
-- 부품이 고정 해제될 때...
part.BrickColor = BrickColor.new("밝은 노랑")
part.Material = Enum.Material.Wood
end
end
local function onToggle()
-- 고정 속성을 전환
part.Anchored = not part.Anchored
-- 벽돌의 시각적 상태 업데이트
updateVisuals()
end
-- 업데이트 후 클릭 수신 시작
updateVisuals()
cd.MouseClick:Connect(onToggle)BackParamA
BackParamB
BackSurfaceInput
BottomParamA
BottomParamB
BottomSurfaceInput
brickColor
CanCollide
코드 샘플
사라지는 문
-- 긴 부품 안에 스크립트를 붙여넣으세요
local part = script.Parent
local OPEN_TIME = 1
-- 현재 문을 열 수 있는가에 대한 질문
local debounce = false
local function open()
part.CanCollide = false
part.Transparency = 0.7
part.BrickColor = BrickColor.new("검은색")
end
local function close()
part.CanCollide = true
part.Transparency = 0
part.BrickColor = BrickColor.new("밝은 파란색")
end
local function onTouch(otherPart)
-- 문이 이미 열려 있다면 아무 것도 하지 않음
if debounce then
print("D")
return
end
-- 인간형에 의해 터치되었는지를 확인합니다
local human = otherPart.Parent:FindFirstChildOfClass("Humanoid")
if not human then
print("인간이 아닙니다")
return
end
-- 문 열기 시퀀스를 수행합니다
debounce = true
open()
task.wait(OPEN_TIME)
close()
debounce = false
end
part.Touched:Connect(onTouch)
close()CFrame
코드 샘플
부품 CFrame 설정
local part = script.Parent:WaitForChild("Part")
local otherPart = script.Parent:WaitForChild("OtherPart")
-- 부품의 CFrame을 (0, 0, 0)로 회전 없이 재설정합니다.
-- 이것은 때때로 "정체성" CFrame이라고 불립니다.
part.CFrame = CFrame.new()
-- 특정 위치(X, Y, Z)로 설정합니다.
part.CFrame = CFrame.new(0, 25, 10)
-- 위와 동일하지만 Vector3를 사용합니다.
local point = Vector3.new(0, 25, 10)
part.CFrame = CFrame.new(point)
-- 부품의 CFrame을 한 지점에 두고 다른 지점을 바라봅니다.
local lookAtPoint = Vector3.new(0, 20, 15)
part.CFrame = CFrame.lookAt(point, lookAtPoint)
-- 부품의 CFrame을 로컬 X 축을 기준으로 pi/2 라디안 회전합니다.
part.CFrame = part.CFrame * CFrame.Angles(math.pi / 2, 0, 0)
-- 부품의 CFrame을 로컬 Y 축을 기준으로 45도 회전합니다.
part.CFrame = part.CFrame * CFrame.Angles(0, math.rad(45), 0)
-- 부품의 CFrame을 전역 Z 축을 기준으로 180도 회전합니다 (순서에 주의하세요!).
part.CFrame = CFrame.Angles(0, 0, math.pi) * part.CFrame -- Pi 라디안은 180도에 해당합니다.
-- 두 개의 CFrame을 구성하는 것은 * (곱셈 연산자)를 사용하여 수행됩니다.
part.CFrame = CFrame.new(2, 3, 4) * CFrame.new(4, 5, 6) --> CFrame.new(6, 8, 10)과 같습니다.
-- 대수적 곱셈과 달리, CFrame 구성은 비가환적입니다: a * b가 반드시 b * a는 아닙니다!
-- *를 일련의 순서가 있는 동작으로 생각하세요. 예를 들어, 다음 줄은 서로 다른 CFrame을 생성합니다:
-- 1) 부품을 X축으로 5 단위 슬라이드합니다.
-- 2) 부품을 Y축 기준으로 45도 회전합니다.
part.CFrame = CFrame.new(5, 0, 0) * CFrame.Angles(0, math.rad(45), 0)
-- 1) 부품을 Y축 기준으로 45도 회전합니다.
-- 2) 부품을 X축으로 5 단위 슬라이드합니다.
part.CFrame = CFrame.Angles(0, math.rad(45), 0) * CFrame.new(5, 0, 0)
-- "CFrame 나누기"는 없지만, 대신 "역 연산 수행하기"입니다.
part.CFrame = CFrame.new(4, 5, 6) * CFrame.new(4, 5, 6):Inverse() --> CFrame.new(0, 0, 0)과 같습니다.
part.CFrame = CFrame.Angles(0, 0, math.pi) * CFrame.Angles(0, 0, math.pi):Inverse() --> CFrame.Angles(0, 0, 0)과 같습니다.
-- 다른 부품에 상대적으로 부품을 배치합니다 (이 경우, 우리 부품을 otherPart 위에 놓습니다).
part.CFrame = otherPart.CFrame * CFrame.new(0, part.Size.Y / 2 + otherPart.Size.Y / 2, 0)CollisionGroup
코드 샘플
물리 서비스:충돌 그룹 등록
local PhysicsService = game:GetService("PhysicsService")
local collisionGroupBall = "CollisionGroupBall"
local collisionGroupDoor = "CollisionGroupDoor"
-- 충돌 그룹 등록
PhysicsService:RegisterCollisionGroup(collisionGroupBall)
PhysicsService:RegisterCollisionGroup(collisionGroupDoor)
-- 부품을 충돌 그룹에 할당
script.Parent.BallPart.CollisionGroup = collisionGroupBall
script.Parent.DoorPart.CollisionGroup = collisionGroupDoor
-- 그룹을 서로 충돌하지 않도록 설정하고 결과 확인
PhysicsService:CollisionGroupSetCollidable(collisionGroupBall, collisionGroupDoor, false)
print(PhysicsService:CollisionGroupsAreCollidable(collisionGroupBall, collisionGroupDoor)) --> falseCollisionGroupId
Color
코드 샘플
캐릭터 건강 몸 색상
-- StarterCharacterScripts 내의 스크립트에 붙여넣기
-- 그런 다음 게임을 플레이하고 캐릭터의 건강을 조정합니다
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
-- 건강 비율에 따라 애니메이션을 통해 색상을 생성합니다
-- 색상은 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
코드 샘플
사용자 정의 물리 속성 설정
local part = script.Parent
-- 이 코드는 파트를 가볍고 탄력 있게 만듭니다!
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
코드 샘플
재귀 잠금 해제
-- 잠금을 해제할 모델 내 스크립트에 붙여넣기
local model = script.Parent
-- 이 함수는 모델의 계층을 재귀적으로 탐색하고
-- 마주치는 모든 부품의 잠금을 해제합니다.
local function recursiveUnlock(object)
if object:IsA("BasePart") then
object.Locked = false
end
-- 객체의 자식에게 동일한 함수를 호출합니다
-- 객체에 자식이 없으면 재귀 과정이 중지됩니다
for _, child in pairs(object:GetChildren()) do
recursiveUnlock(child)
end
end
recursiveUnlock(model)Orientation
코드 샘플
부품 회전기
local part = script.Parent
local INCREMENT = 360 / 20
-- 부품을 계속 회전시킴
while true do
for degrees = 0, 360, INCREMENT do
-- Y축 회전만 설정
part.Rotation = Vector3.new(0, degrees, 0)
-- 이를 수행하는 더 나은 방법은 CFrame을 설정하는 것입니다.
--part.CFrame = CFrame.new(part.Position) * CFrame.Angles(0, math.rad(degrees), 0)
task.wait()
end
endPivotOffset
코드 샘플
피벗 재설정
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)시계 바늘
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
-- 다이얼 생성
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
-- 바늘 생성
local hourHand = createHand(7, 1, 0)
local minuteHand = createHand(10, 0.6, 0.1)
local secondHand = createHand(11, 0.2, 0.2)
-- 시계 실행
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
코드 샘플
크기 조절 핸들
-- 여러 종류의 BasePart에 이 스크립트를 넣으세요, 예를 들어
-- Part, TrussPart, WedgePart, CornerWedgePart 등.
local part = script.Parent
-- 이 부품에 대한 핸들 객체를 생성합니다.
local handles = Instance.new("Handles")
handles.Adornee = part
handles.Parent = part
-- 이 핸들에 적용 가능한 면을 수동으로 지정합니다.
handles.Faces = Faces.new(Enum.NormalId.Top, Enum.NormalId.Front, Enum.NormalId.Left)
-- 또는 부품의 크기를 조정할 수 있는 면을 사용하세요.
-- 부품이 두 개의 크기 차원만 있는 TrussPart인 경우
-- 크기가 2인 경우 ResizeableFaces에는 두 개의
-- 활성화된 면만 있습니다. 다른 부품의 경우 모든 면이 활성화됩니다.
handles.Faces = part.ResizeableFacesRightParamA
RightParamB
RightSurfaceInput
RotVelocity
Size
코드 샘플
피라미드 빌더
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 = "Tower"
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
-- 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
코드 샘플
사라지는 문
-- 긴 부품 안에 스크립트를 붙여넣으세요
local part = script.Parent
local OPEN_TIME = 1
-- 현재 문을 열 수 있는가에 대한 질문
local debounce = false
local function open()
part.CanCollide = false
part.Transparency = 0.7
part.BrickColor = BrickColor.new("검은색")
end
local function close()
part.CanCollide = true
part.Transparency = 0
part.BrickColor = BrickColor.new("밝은 파란색")
end
local function onTouch(otherPart)
-- 문이 이미 열려 있다면 아무 것도 하지 않음
if debounce then
print("D")
return
end
-- 인간형에 의해 터치되었는지를 확인합니다
local human = otherPart.Parent:FindFirstChildOfClass("Humanoid")
if not human then
print("인간이 아닙니다")
return
end
-- 문 열기 시퀀스를 수행합니다
debounce = true
open()
task.wait(OPEN_TIME)
close()
debounce = false
end
part.Touched:Connect(onTouch)
close()Velocity
메서드
AngularAccelerationToTorque
ApplyImpulseAtPosition
BreakJoints
breakJoints
CanSetNetworkOwnership
반환
코드 샘플
부품의 네트워크 소유권을 설정할 수 있는지 확인
local part = workspace:FindFirstChild("Part")
if part and part:IsA("BasePart") then
local canSet, errorReason = part:CanSetNetworkOwnership()
if canSet then
print(part:GetFullName() .. "의 네트워크 소유권을 변경할 수 있습니다!")
else
warn("" .. part:GetFullName() .. "의 네트워크 소유권을 변경할 수 없습니다: " .. errorReason)
end
endGetClosestPointOnSurface
GetConnectedParts
GetJoints
BasePart:GetJoints():Instances
반환
Instances
GetMass
getMass
GetNoCollisionConstraints
BasePart:GetNoCollisionConstraints():Instances
반환
Instances
GetRenderCFrame
GetRootPart
GetTouchingParts
BasePart:GetTouchingParts():Instances
반환
Instances
GetVelocityAtPosition
IntersectAsync
BasePart:IntersectAsync(
매개 변수
parts:Instances |
| 기본값: "Default" |
| 기본값: "Automatic" |
반환
MakeJoints
makeJoints
Resize
매개 변수
반환
resize
SetNetworkOwner
SetNetworkOwnershipAuto
BasePart:SetNetworkOwnershipAuto():()
반환
()
SubtractAsync
BasePart:SubtractAsync(
매개 변수
parts:Instances |
| 기본값: "Default" |
| 기본값: "Automatic" |
반환
코드 샘플
BasePart:SubtractAsync()
local Workspace = game:GetService("Workspace")
local mainPart = script.Parent.PartA
local otherParts = { script.Parent.PartB, script.Parent.PartC }
-- 빼기 작업 수행
local success, newSubtract = pcall(function()
return mainPart:SubtractAsync(otherParts)
end)
-- 작업이 성공하면 동일한 위치에 배치하고 작업공간에 부모로 설정
if success and newSubtract then
newSubtract.Position = mainPart.Position
newSubtract.Parent = Workspace
end
-- 작업 후에 그대로 남아 있는 원래 파트 파괴
mainPart:Destroy()
for _, part in otherParts do
part:Destroy()
endTorqueToAngularAcceleration
UnionAsync
BasePart:UnionAsync(
매개 변수
parts:Instances |
| 기본값: "Default" |
| 기본값: "Automatic" |
반환
코드 샘플
BasePart:UnionAsync()
local Workspace = game:GetService("Workspace")
local mainPart = script.Parent.PartA
local otherParts = { script.Parent.PartB, script.Parent.PartC }
-- 유니온 작업 수행
local success, newUnion = pcall(function()
return mainPart:UnionAsync(otherParts)
end)
-- 작업이 성공하면 원래 위치에 배치하고 작업공간에 부모로 설정합니다
if success and newUnion then
newUnion.Position = mainPart.Position
newUnion.Parent = Workspace
end
-- 작업 후에도 남아 있는 원래 부품 파괴
mainPart:Destroy()
for _, part in otherParts do
part:Destroy()
end이벤트
LocalSimulationTouched
OutfitChanged
StoppedTouching
Touched
매개 변수
코드 샘플
접촉하는 부품 수
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("접촉 시작: " .. otherPart.Name)
numTouchingParts = numTouchingParts + 1
tl.Text = numTouchingParts
end
local function onTouchEnded(otherPart)
print("접촉 종료: " .. otherPart.Name)
numTouchingParts = numTouchingParts - 1
tl.Text = numTouchingParts
end
part.Touched:Connect(onTouch)
part.TouchEnded:Connect(onTouchEnded)모델 터치됨
local model = script.Parent
local function onTouched(otherPart)
-- 모델 인스턴스가 자신과 접촉하는 것을 무시합니다
if otherPart:IsDescendantOf(model) then
return
end
print(model.Name .. "가 " .. otherPart.Name .. "에 충돌했습니다")
end
for _, child in pairs(model:GetChildren()) do
if child:IsA("BasePart") then
child.Touched:Connect(onTouched)
end
endTouchEnded
매개 변수
코드 샘플
접촉하는 부품 수
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("접촉 시작: " .. otherPart.Name)
numTouchingParts = numTouchingParts + 1
tl.Text = numTouchingParts
end
local function onTouchEnded(otherPart)
print("접촉 종료: " .. otherPart.Name)
numTouchingParts = numTouchingParts - 1
tl.Text = numTouchingParts
end
part.Touched:Connect(onTouch)
part.TouchEnded:Connect(onTouchEnded)