I’m doing an npc that attacks you but I need that when it touches you to always teleport behind you, could someone help me?
use Humanoid.Touched then Humanoid:MoveTo to teleport a npc to a specific position.
https://developer.roblox.com/en-us/api-reference/event/Humanoid/Touched
https://developer.roblox.com/en-us/api-reference/function/Model/MoveTo
If you want a position relative to the player you need to use
local Position = HumanoidRootPart.CFrame:PointToWorldPosition(Vector3.new(0,0,-5))
This line returns a Vector Position 5 studs behind the player. If you want it facing towards the player use
local CoordinateFrame = CFrame.lookAt(Position,HumanoidRootPart.Position
This line return the CFrame looking at the player.
This would only teleport the NPC 5 studs away from the player on the Z axis. You’ll need to use LookVector
.
local char = yourCharacterHere
local hrp = char:WaitForChild('HumanoidRootPart')
local NPC = yourNPCHere
local NPChrp = NPC:WaitForChild('HumanoidRootPart')
NPChrp.Touched:Connect(function(hit)
if hit:IsDescendantOf(char) then
local cf = hrp.CFrame + (hrp.CFrame.LookVector * -5)
NPC:SetPrimaryPartCFrame(cf)
end
end)
if you want the NPC to look at the character after teleporting, you can use CFrame.lookAt
, as mentioned above
NPC:SetPrimaryPartCFrame(CFrame.lookAt(cf.Position, hrp.Position))
I am sorry what do you mean by only on the Z axis? Isn’t that what he wants?
Depending on the direction the player is facing, the Z axis may or may not be going directly behind them. If the player isn’t lined up perfectly with the Z axis, the NPC may teleport to the left, right, or in front of the character. While the XYZ axes are global, the rootpart’s LookVector is dependent on which direction the player faces, so using the rootpart’s CFrame.LookVector
is accurate every time.
Sorry I am not understanding what you mean by the Z axis changing. Z axis is forwards right? So just negate that and it will be behind him.
Wouldn’t it just be easier to use PointToWorldSpace or even ToWorldSpace with the offset?
I believe both solutions work. I am not understanding why you think that mine won’t work.