I’ve been following this guy’s tutorials. They’re really cool! And they’ve been helping me learn JavaScript(As I’m used to Java).
The only problem I’m having is that when I walk, it gradually speeds up. But then it catches and restarts my acceleration. I’ll post my code up. (:
#pragma strict
var walkAcceleration : float = 5f;
var walkFriction : float = 5f;
var walkFrictionDampX : float;
var walkFrictionDampZ : float;
var cameraObject : GameObject;
var maxWalkSpeed : float = 20f;
var horizontalMovement : Vector3;
var jumpVelocity : float = 20;
var grounded : boolean = false;
var maxSlope : float = 60;
function Update () {
horizontalMovement = Vector2(rigidbody.velocity.x, rigidbody.velocity.z);
if(horizontalMovement.magnitude > maxWalkSpeed)
{
horizontalMovement = horizontalMovement.normalized;
horizontalMovement *- maxWalkSpeed;
}
rigidbody.velocity.x = horizontalMovement.x;
rigidbody.velocity.z = horizontalMovement.y;
if(Input.GetAxis("Horizontal") == 0 && Input.GetAxis("Vertical") == 0 && grounded)
{
rigidbody.velocity.x = Mathf.SmoothDamp(rigidbody.velocity.x, 0, walkFrictionDampX, walkFriction);
rigidbody.velocity.z = Mathf.SmoothDamp(rigidbody.velocity.z, 0, walkFrictionDampZ, walkFriction);
}
transform.rotation = Quaternion.Euler(0, cameraObject.GetComponent(MouseLooking).currentYRotation, 0);
rigidbody.AddRelativeForce(Input.GetAxis("Horizontal") * walkAcceleration * Time.deltaTime, 0, Input.GetAxis("Vertical") * walkAcceleration * Time.deltaTime);
if(Input.GetButtonDown("Jump") && grounded)
{
rigidbody.AddForce(0, jumpVelocity, 0);
}
}
function OnCollisionStay(collision : Collision)
{
for(var contact : ContactPoint in collision.contacts)
{
if(Vector3.Angle(contact.normal, Vector3.up) < maxSlope)
grounded = true;
}
}
function OnCollisionExit()
{
grounded = false;
}