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

BodyForce applied to object in the wrong direction?

Asked by 4 years ago

Hi, I'm trying to make a script that throws a ball in the direction the player clicked. What I have so far is

Local Script:

local player = game.Players.LocalPlayer
local mouse = player:GetMouse()
local mousepos = mouse.Hit.p
local handle = script.Parent
local tool = handle.Parent

local RS = game:GetService("ReplicatedStorage")
local ThrowBallEvent = RS:WaitForChild("ThrowBall")

tool.Activated:connect(function()
    ThrowBallEvent:FireServer(tool, mousepos)   
    tool:Destroy()  
end)

Server Script:

local RS = game:GetService("ReplicatedStorage")
local ThrowBallEvent = RS:WaitForChild("ThrowBall")

local function ThrowBall(player, tool, mousepos)

    local ball = tool:clone()
    ball.Parent = game.Workspace

    local rootpart = player.Character:FindFirstChild("HumanoidRootPart")
    local humanoid = player.Character:FindFirstChild("Humanoid")
    local head = player.Character:FindFirstChild("Head")

    local newhandle = ball:WaitForChild("Handle")
    newhandle.Position = head.Position + head.CFrame.lookVector * 4
    newhandle.CanCollide = true

    local force = Instance.new("BodyForce", newhandle)
    local targetpos = mousepos
    local initialpos = rootpart.Position
    local direction = (mousepos - initialpos).unit
    force.Force = direction * 300

end

ThrowBallEvent.OnServerEvent:Connect(ThrowBall)

The ball is thrown, but the direction of the force is completely arbitrary. Sometimes the ball will take off to the left, sometimes it'll go behind me, and sometimes it'll go straight. Any idea on why it's acting like this and not just going where I click?

1 answer

Log in to vote
0
Answered by
AizakkuZ 226 Moderation Voter
4 years ago
Edited 4 years ago
local initialpos = rootpart.Position

^ Here you basically told it to go in the direction of ur rootparts position

mousepos - initialpos).unit

^ Basically these Two lines make the whatever go from ur mouse pos subtracted by ur HumanoidRootParts Position instead u wanna use CFrame then convert that to Vector like so

local initialpos = rootpart.CFrame.LookVector --LOOKVECTOR = INFRONT OF YOU

Hope this helps I'm not too good with Vector3s and position so I apologize if any of it was wrong as you were using Position for shooting something so it's confusing me also there r multiple Vectors LookVector, UpVector and RightVector

0
Also again i'm not too good with Positioning but wouldn't ur Mouse - your humroot make it shoot from ur mouse to your humroot idk tho again your code confuses me lmao AizakkuZ 226 — 4y
0
Didn't work unfortunately... only ensured that the ball spawned in front of me but the force was still applied pretty randomly. jdmartine_z 15 — 4y
Ad

Answer this question