How do I move a part using OnTouch?

Hello everyone! I am currently having trouble making a part move when it is touched, any help?

local part = script.Parent

local function onTouch(otherPart) 
	 if otherPart.Name == 'Hitzone' then
		print("Unanchored") 
  part.Anchored = false
 end
end
part.Touched:Connect(onTouch)

How can I make it so that when the part gets touched it moves in the opposite direction from where it was touched?

3 Likes

Use velocity. It makes parts move.

2 Likes

Use a body force and find the two part’s positions to calculate an axis. You can then use this axis to calculate the force for the body force, and make the part move that way.

2 Likes

Try using a body object or the velocity of the unanchored part combined with a CFrame lookvector that can be used to get the backwards axis relative to the two.
Something like:

local cfram = CFrame.new(part.Position,otherPart.Position)
part.Velocity = cfram.lookVector * -60 --change the control strength of velocity

This’ll move the part backwards based on the relative position between the part that touched it and the unanchored part. Essentially it gets a lookat CFrame between the two parts and then uses the direction that CFrame is facing to multiply it to go backwards.

2 Likes

The script works but it keeps moving backwards forever, is there a way to change how far it moves back?

Edit: I figured it out, thank you!

1 Like