Hi,
I’m trying to create my own simple character controller without using rigidbodies.
While I can successfully anticipate a collision and prevent movement, I can’t figure out a good way to “slide” off collisions - the character simply stops completely on any collision. I imagine I’d have to use the collision normal to update the post-collision position, but everything I tried failed.
Here’s a (very simple) sample code.I plan on adding ground detection, jumping, etc, only after getting the collisions right.
#pragma strict
var speed:float = 2;
var colliderRadius:float = 1;
var colliderCenter:Vector3;
var colliderMask:LayerMask = -1;
private var vector:Vector3;
private var hit:RaycastHit;
function Update () {
if ( Input.GetAxis ("Horizontal") < 0 ) {
vector.x = ( -speed );
} else if ( Input.GetAxis ("Horizontal") > 0 ) {
vector.x = ( speed );
} else {
vector.x = 0;
}
if ( Input.GetAxis ("Vertical") > 0 ) {
vector.y = ( speed );
} else if ( Input.GetAxis ("Vertical") < 0 ) {
vector.y = ( -speed );
} else {
vector.y = ( 0 );
}
if ( Physics.SphereCast( transform.position + colliderCenter, colliderRadius, vector.normalized, hit, vector.magnitude * Time.deltaTime, colliderMask ) ) {
//Collision would happen if I moved
} else {
//No Collision! Let's move.
transform.Translate( vector * Time.deltaTime );
}
}
Any help is appreciated.Thanks!