- Home /
How can I make my character walk along the slope?
Moving a RigidBody-equipped character from the ground, or "climbing" the slope did not have much of a problem. Exactly, there was not a big problem with the Y-axis velocity value being 0 when you climbed the surface.
The problem is that if you go down the slope, CollisionExit and CollisionEnter are constantly called to see if the angle between the surface and the ground is different and the player does not seem to make the right move.
Here is the code related to my movement and rotation. What parts can be modified to fix the problem when moving on the surface?
int Y_Rot=0;//The Y value of EulerAngles. 0 == right, 180 = left
float Speed=3;
Transform floor;
private void OnCollisionEnter2D(Collision2D collision) => floor = collision.transform;
private void OnCollisionStay2D(Collision2D collision)=> floor = collision.transform;
private void OnCollisionExit2D(Collision2D collision)=> floor = null;
private void FixedUpdate()
{
Vector3 look = transform.eulerAngles;
//If the character is standing on the ground
if (floor != null)
{
//If the character is looking to the left, inverse the current ground landing to get the EulerAngle value.
look = (look.y == 0 ? floor.rotation : Quaternion.Inverse(floor.rotation)).eulerAngles;
look.y = Y_Rot;
//Set the velocity value to 0 to prevent the character from falling when the character is facing up. (The character could not climb the slope when annotating that part)
if(Rigidbody.velocity.y < 0 && transform.right.y >= 0)Rigidbody.velocity = Vector2.zero;
}
//When the character is floating in the air
else
{
look.y = Y_Rot;
look.z = 0;
}
transform.rotation = Quaternion.Euler(look);
}
//basedir: Indicates the direction of movement of the x axis when the character is on the ground.
public void SetMoveDir(Vector3 basedir)
{
Vector2 dir = basedir;
//If there is a movement direction, adjust the Y-axis rotation value to match that direction.
if(dir.x!=0) Y_Rot = dir.x == 1 ? 0 : 180;
//If it touches the ground surface, it moves to fit the ground surface. If it does not touch the ground surface, it moves to the default direction.
if (floor != null)
{
if (dir.x != 0)
{
FixedUpdate(); //Manually invoke FixedUpdate to rotate to the angle of the surface.
dir = transform.right.normalized * Time.deltaTime;
dir.x *= Speed;
Rigidbody.position += dir;
}
}
else Rigidbody.position += dir * Time.deltaTime;
}
Answer by Heukhyeon · Dec 27, 2017 at 01:04 PM
I got the answer. We corrected the error by reading the Bound value of the Renderer rather than getting the bottom from the collision, and calculating the height and processing it by directly racasting it.
Your answer
![](https://koobas.hobune.stream/wayback/20220612145305im_/https://answers.unity.com/themes/thub/images/avi.jpg)