- Home /
Prevent Rigidbody from Shooting Off Slopes
I've seen a couple posts about this but I don't think I can implement them into my movement system.
Does anyone have a good solution for this?
Here is how I'm moving currently, it keeps the character on the ground when walking up/down slopes, but sometimes I still shoot off at the crest of slopes, since I'm adding force to the X-Axis.
Code (CSharp):
bool downHill = (straffe >= 0 && slopeHit.normal.x >= 0 || straffe <= 0 && slopeHit.normal.x <= 0); //Checking the ground to see if we're going uphill or downhill.
float f = straffe;
f = downHill ? f : f / 1.5f;
Vector3 targetVel = new Vector3(f, 0, 0);
Vector3 slopeMove = Vector3.ProjectOnPlane(targetVel, slopeHit.normal);
Vector3 velChange = slopeMove - rB.velocity;
rB.AddForce(velChange, ForceMode.VelocityChange);
If there are no good physics solutions to this problem than I think clamping the player to the ground would be good as well... not quite sure how to do that though.
Any thoughts? Thanks!
Answer by Kaldrin · Apr 09, 2021 at 01:28 PM
Hey! I am not quite sure what you mean by shooting off slopes? Could you provide with an example of what is happening?
This image explains well.
Okay I understand better It's weird that it's behaving this way even though you tell it to stick to the ground (If I understand correctly your code)
I am not familiar with the ForceMode and ProjectOnPlane things so I'm not sure if I can suggest a better solution but clamping it with a raycast is probably the best idea. Is it 2D or 3D ?
2.5D so I'm just using the X/Y axis with 3D tools.
I think the issue is that I'm projecting straight down so I cannot predict upco$$anonymous$$g changes to the grounds terrain.
I've accomplished this with a spider I made by adding an empty game object a bit forward of my character as something like a counter-weight. Unfortunately I don't have access to the code and setup till I'm out of work but it might be an idea.
Your answer
![](https://koobas.hobune.stream/wayback/20220613032019im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Get result (force & torque) of AddForceAtPosition? 2 Answers
Why is force only being added in the same direction? 1 Answer
How do I add force To rigidbody based On Character's Walking direction? 0 Answers
Prevent Rigidbody From Rotating 3 Answers
Erratic Physics behaviour while testing in 2 computers 0 Answers