I’ve been trying to make a shooting mechanic in my hockey game but whenever you shoot the puck, it goes to the right of you instead of where you’re aiming your mouse at. Any way i can make the puck go to where my mouse is?
local pushforce = Instance.new("BodyVelocity")
pushforce.Name = "Shot"
pushforce.MaxForce = Vector3.new(1000000000000,1000000000000000,10000000000000000)
pushforce.Velocity = Vector3.new(pos, power / 5, power * 1.5)
pushforce.P = Vector3.new(power , power / 2, power * 2)
if game.Workspace.Puck:WaitForChild("Weldd").Part0 == script.Parent.Hold then
script.Parent.NoPick.Value = true
game.Workspace.Puck.Weldd:Destroy()
pushforce.Parent = game.Workspace.Puck
game.Workspace.Puck.CanCollide = true
wait(.25)
pushforce:Destroy()
wait(.75)
script.Parent.NoPick.Value = false
end
The basic idea is that you multiply the direction of the shot with the power you want:
local deltaPos = mouseHitPosition - puckPosition -- Vector3 difference between two positions
local direction = deltaPos.Unit -- unit circle representation of direction
pushforce.Velocity = direction * power -- make the force stronger/weaker by multiplying it by the power
You’ll have to play around with the custom physical properties of the puck and the ice as well as lowering the gravity of the workspace to find a configuration that looks and performs desirably. I find that messing around and observing the changes something does is a very good way of eventually understanding how the maths and physics work.
This script has fixed a small issue of the puck only going to one spot but now it only goes to a random position and not the mouses position or near it, sometimes it goes backwards. Here is the way I inserted the code.
local pushforce = Instance.new("BodyVelocity")
local deltaPos = pos - game.Workspace.Puck.Position -- Pos = mousehitposition
local direction = deltaPos.Unit
pushforce.Velocity = direction * deltaPos
pushforce.Name = "Shot"
pushforce.MaxForce = Vector3.new(1000000000000,1000000000000000,10000000000000000)
pushforce.P = Vector3.new(power, power / 2, power * 2)
Your issue isn’t making the puck move so your forces and velocities are fine, it’s just your direction, so focus on fixing that issue.
In this line you explain what pos is, but how and where is pos defined? local deltaPos = pos - game.Workspace.Puck.Position -- Pos = mousehitposition
@pullman45 has given you a simple way of figuring it out with this line of code: local deltaPos = mouseHitPosition - puckPosition -- Vector3 difference between two positions
The value you multiply “deltaPos” by represents the magnitude (range) of the directional vector, in the above example the magnitude would be a range of 100 studs.