How can I make it so that the base gif the car or the wheels of the car are always exerting a force in the direction where the road is so that it always stays o the road, even if it’s upside down?
Use raycasting: WorldRoot | Roblox Creator Documentation, cause the return value RaycastResult | Roblox Creator Documentation yields ‘Normal’. You can check if a raycast hits the road and then see what normal it returns. This way, you can calculate a normal from your car to the road.
local raycastParams = RaycastParams.new()
raycastParams.FilterType = Enum.RaycastFilterType.Blacklist
raycastParams.FilterDescendantsInstances = {script.Parent}
raycastParams.IgnoreWater = true
-- Cast the ray
local carPrimaryPart = script.Parent.PrimaryPart
local TRACTION_FORCE = 10
local RAYCAST_LENGTH = 30
local function getTractionForce()
local raycastNormal = -part.CFrame.UpVector
local raycastResult = workspace:Raycast(
part.Position,
raycastNormal * RAYCAST_LENGTH,
raycastParams
)
if raycastResult then
-- Get the normal from the car to the road
local forceNormal = -(raycastResult.Normal - raycastNormal).Unit
return forceNormal * TRACTION_FORCE
else
-- You are not on a road
return Vector3.new()
end
end
How will this help the car to always stay on the ground?
You can add a VectorForce to your car and update it like this:
local runService = game:GetService('RunService')
local vectorForce = script.Parent.PrimaryPart.VectorForce
runService.Heartbeat:Connect(function()
vectorForce.Force = getTractionForce()
end)
This force will try to make your car stick to the ground. I have not tested my code, but I think it might work. It is recommendable to set the center of force to the center of mass of your car to get rid of unwanted torque.
ok, so I add
this piece of code to the end of the first one?
Edit: If this works I’ll mark you as a solution
Yes, but you have to correct the primary part related code. Also, I think that the TRACTION_FORCE is a bit low, so you might want to mess around with that.
I made a minor mistake in the forceNormal definition. / 2 should have been .Unit as edited.
I did some testing and I came up with this:
CarTraction.rbxl (33.0 KB)
Things to notice are:
- Implementation of course
- Improved friction of the wheels
- You can drive upside down, which you can test with the half loop
The car is a bit… limited, but you can see my idea.
Really? But this is physics related mainly
Still involves scripting… So
And it also involves physics, body thrust is physics, force is physics, but I guess it could be in either?
What is this part supposed to be?
The output says that I’m attempting to index nil with CFrame, are they supposed to be the wheels?
Oh, no that is basically your primary part (car bottom, body or whatever you want to call it).