You need to project your velocity onto the slope of the terrain, otherwise you’re just moving your tank into it as you never factor in the collision. You can find the slope with many different methods, but since you’re in a tank I assume the tracks have some kind of ray cast or collision detection.
With that collision detection, you’ll have a surface normal in the result, RaycastResult.Normal
which you may then use to project your velocity so that you move relative to the incline.
You can project a vector on a normal with the following code.
local velocity = Vector3.new(0, 0, 100)
velocity = velocity - normal * velocity:Dot(normal)
This will not preserve your magnitude, however it may give you realistic results since in real life you would face resistance due to gravity. However, assuming you already account for this for more control you can just normalise it and bring it back up.
local velocity = Vector3.new(0, 0, 100)
-- If your velocity is 0, we'll get NaN when normalising.
if velocity ~= Vector3.zero then
velocity = (velocity - normal * velocity:Dot(normal)).Unit * velocity.Magnitude
end
Possible issues
Since you’re working with Terrain, you’ll likely want to get a sample of the normals in a space instead with multiple raycasts so that you can get the average. The reason being is that the surface normal is taken from the specific triangle it hits, meaning this could be wildly inaccurate if your terrain isn’t perfectly flat.
Edit
For further clarification, it sounds like you intend for Roblox’s physics to take over and adjust the rotation of the tank, but this is unreliable which is why you’re having issues.
This is because the linearVelocity will try to move you in a direction with a specific amount of force, this doesn’t guarantee you’ll face enough angular force from a collision to push you around. You should really avoid setting it relative to the attachment for this reason and instead work out rotation yourself.
It can be tricky to predict how much force you need to rotate as this is usually calculated with the moment of inertia or in other words angular mass, which changes depending on the shape of an object. There are formulas to get a rough estimate if you’re interested though. Moments of inertia