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?
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.
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.