Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

How to make a part move foward in the direction its pointed at?

Asked by 4 years ago
Edited 4 years ago

So I can move three directions, x, y, z. But what I need to know is instead of moving it directly in a direction, like move in z axis, Is if I can if the objects rotation is right, it move right, and if the object is rotated left, it moves left. I kind of don't know how to explain it properly, but I hope you get it.

obj.Position = Vector3.new(player.Character.Head.Position.X,player.Character.Head.Position.Y ,player.Character.Head.Position.Z)

Thats the code, just make it move foward in the certain direction its pointing at (the players head).

1 answer

Log in to vote
0
Answered by 4 years ago

Your original code

obj.Position = Vector3.new(player.Character.Head.Position.X,player.Character.Head.Position.Y ,player.Character.Head.Position.Z)

Can actually just be equated to

obj.Position = player.Character.Head.Position

And it will do the same thing.

Now as for moving a part in the direction the player's head is facing, we'll need the LookVector of the head, and the easiest way to get a LookVector is to get the CFrame of the head.

You might be wondering: What's a LookVector? A LookVector is the forward direction of a CFrame. In other words, it points at something. A LookVector is a Vector3 with a Magntiude of 1.

Now that we know that, we can implement it. This is the code I wrote to move a part so and so amount of studs in the direction our character is facing.

--//This is the code for what you asked for
local Const = 5 --//How many studs forward do you want obj to travel?

obj.Position = obj.Position + player.Character.Head.CFrame.LookVector * Const

You might be thinking: Why are we multiplying the LookVector? The answer is because the LookVector's magnitude is only 1, if we don't multiply it, it will only go in the direction we are facing one stud.

You also might be wondering why there is a obj.Position = obj.Position in there, doesn't that seem redundant?

What I am doing is incrementing the variable. Think of it like this:

local var = 5
var = var + 5 --//var is now equal to 10

--//Is like

local var2 = 5
var2 = 5 + 5 --//var2 is also equal to 10

So all I'm doing is taking our obj position, and adding the amount of studs I want to move forward by in the direction of our character's head.

If you have any questions, just comment below. I got on a quite weird explanation, I'm really tired so sorry if it doesn't make any sense lol.

0
Thanks for the answer! I'm going to test it out later. therotatedo 19 — 4y
Ad

Answer this question