- Home /
Character moves diagonally backwards while moving side to side on slopes
Hi, i seem to be having a problem with moving a simple character left to right while on a slope. The character (A box at the moment) is a cube with a rigidbody as i'm wanting to use physics.
The character moves fine how it's supposed to on the flat (forward/backwards/left/right), but when i go on a bit of a slope and try to strafe (left/right) the character does move left/right but also moves backwards down the slope.
Heres the code that i'm using for controlling the character
var currentPosition : Vector3;
function Awake(){ //Get Start Position currentPosition = transform.position; }
function Update () {
if(Input.anyKey)
{
if(Input.GetKey(KeyCode.UpArrow))
transform.Translate(0,0,10 * Time.deltaTime);
if(Input.GetKey(KeyCode.DownArrow))
transform.Translate(0,0,-10 * Time.deltaTime);
if(Input.GetKey(KeyCode.LeftArrow))
transform.Translate(-10 * Time.deltaTime,0,0);
if(Input.GetKey(KeyCode.RightArrow))
transform.Translate(10 * Time.deltaTime,0,0);
currentPosition = transform.position;
}
//Stop from sliding down the slope
transform.position.x = currentPosition.x;
transform.position.z = currentPosition.z;
//Stop from falling over (Only temp)
transform.rotation.x = 0;
transform.rotation.y = 0;
transform.rotation.z = 0;
}
Any help on how to solve this would be greatly appreciated :)
Thanks, Shogun
Answer by Bampf · May 02, 2011 at 08:05 PM
The sliding is caused by the rigidbody, and from a physics point of view it makes some sense. When you are on a slope you slide down it. When the player moves forward or backward it's not noticeable but side to side, there's nothing to cancel out the movement downwards. Some possible solutions:
1) You may want to get rid of the rigidbody. Unity's documentation for character controller suggests an alternative:
"If you want to push Rigidbodies or objects with the Character Controller, you can apply forces to any object that it collides with via the OnControllerColliderHit() function through scripting."
2) You could try increasing the drag values on the rigidbody, but that would just make it slide more sluggishly.
3) You could add a physic material to the character's collider and/or the ground. That should let you adjust the amount of total amount of friction.
I note that some FPS games actually allow sliding when the player attempts to walk on a steep slope, so you may not need to completely eliminate it. Depends on your game.
Excellent i've just tried suggestion number one and once i totally get the hang of the Character Controller it will work just how i want it to work, thanks :)
I also tried suggestion number 2 before i posted, but like you say it just made it more sluggish and it just made it slide down the slope slower than before :p