How To Make A Part Bounce of Another Part

I made a script when a player touches a part it flys away from them. I am wanting to know how to add a feature to my script, when the part hits another part it will bounce back or off the part.

I have an idea of how to do it but I don’t know how to do that and if that is the best way to do it.

In the script it bounces of the player but not parts.

How do I accomplish this?

local part = script.Parent -- Assuming the script is a child of the part you want to move
local TweenService = game:GetService("TweenService")

local function onTouch(hit)
	local character = hit.Parent
	local humanoid = character:FindFirstChildOfClass("Humanoid")

	if humanoid then
		-- If a player touches the part, move in the direction the player is facing
		local direction = character:GetPrimaryPartCFrame().lookVector
		local distance = 50 -- Adjust the distance as needed
		local duration = 1 -- Adjust the duration of the tween as needed

		local endPosition = part.Position + direction * distance

		local tweenInfo = TweenInfo.new(duration)
		local goal = {}
		goal.Position = endPosition

		local tween = TweenService:Create(part, tweenInfo, goal)
		tween:Play()
	else
		-- If another part touches the part, bounce back based on the side touched
		local normal = (part.Position - hit.Position).unit
		local reflectDirection = Vector3.new(-normal.X, 0, -normal.Z) -- Reflect on the plane

		local distance = 50 -- Adjust the distance for the bounce back
		local duration = 1 -- Adjust the duration of the tween for the bounce back

		local endPosition = part.Position + reflectDirection * distance

		local tweenInfo = TweenInfo.new(duration)
		local goal = {}
		goal.Position = endPosition

		local tween = TweenService:Create(part, tweenInfo, goal)
		tween:Play()
	end
end

part.Touched:Connect(onTouch)
2 Likes

I remade it so you don’t need a humanoid but I still don’t know how to make it bouce of other parts

local TweenService = game:GetService("TweenService")

local function onTouch(hit)
	local character = hit.Parent
	local tool = character:FindFirstChildOfClass("Tool")

	if tool and tool:FindFirstChild("Handle") then
		local direction = character:GetPrimaryPartCFrame().lookVector
		local distance = 10 -- Adjust the distance as needed
		local duration = 1 -- Adjust the duration of the tween as needed

		local endPosition = part.Position + direction * distance

		local tweenInfo = TweenInfo.new(duration)
		local goal = {}
		goal.Position = endPosition

		local tween = TweenService:Create(part, tweenInfo, goal)
		tween:Play()
	end
end

part.Touched:Connect(onTouch)
1 Like