- Home /
Align child object to grounds normal(slopes)
Hi there. I'm working on a 2d platformer and i am using a rigidbody2d for movement. Moreover, the real character, so the graphics(sprite renderer) is attached as a child object (local position 0,0,0). So i want the child transform (the graphics) to rotate in order to match the angle of the ground/slope while the parent object including all colliders, the rigidbody, etc... shall stay exactly horizontal. I tried several things with raycsts/linecasts to get the normals of the slopes. This works well but setting the rotation of the child transform simply jumps around and glitches everywhere.
So to get this clear: it is only 2d. A 2d collider with a 2d rigidbody, moving over a 2dtilemap with 2d edgecolliders. What might be the best way to align the graphics transform to the slope while maintaining all other rotations/positions?
Answer by The Kracken · Dec 10, 2013 at 02:15 AM
Vector3 groundnormal;
transform.up = groundnormal;
I would expect that to work. Otherwise you can use Mathf.atan2() to get the radian it needs to be at and rotate on the Z-axis.
Answer by zzeettoo · Dec 10, 2013 at 10:56 AM
Basically, that works. The problem itself is not the angle or the aligning but the colliders. I have gravity and for my character a setup of a boxcollider and two circle colliders(2d) at the lowerleft and right ends of the box collider. With a horizontally aligned setup, they walk up and down the slopes perfectly and due to the gravity they slide down a little bit at the slopes. So i wanted to maintain this behaviour and therefore i decided to only rotate(align) the graphics, so the character sprite should rotate but not the whole physics setup. This works somehow, but gets messed up when i change the facing direction of my character (when he walks left instead of right). The calculated normals and angles are obviously still the same and the sprite gets rotated to the wrong side.
When i rotate the whole setup (including rigidbody, colliders, etc...) The rotation works prefectly but physics get messed up as the character won't slowly slide down a slope anymore but make little glitchy jumps untill he reaches even ground again. Thats because the gravity pulls him down and the slope is steep enough to let him "go" down but the friction of its physics material(friction 1) sticks him to the slope. So the force which pulls him down sums up and every few frames he makes a small jump and lands a few pixel down the slope.
Your answer
![](https://koobas.hobune.stream/wayback/20220613123822im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
2D Game, Character Slides off Slopes, Need to be Able to Walk on Them 1 Answer
Handling 2D Slope 1 Answer
Idk what's wrong with my code.. 1 Answer
2D Geometry dash-like ship physics 0 Answers