Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using UnityEngine;
- using System.Collections;
- namespace PlayerController
- {
- [ RequireComponent( typeof( Rigidbody ) ) ]
- public class PlayerMove : MonoBehaviour
- {
- public float walkAcceleration = 20f;
- public float walkDeacceleration = .1f;
- public float maxWalkSpeed = 5f;
- public float jumpForce = 150f;
- public float maxSlope = 75f;
- private Vector2 horizontalMovement;
- private bool isMoving = false;
- private float walkDeaccelerationX = 0f;
- private float walkDeaccelerationZ = 0f;
- private float ref_walkDeaccelerationX = 0f;
- private float ref_walkDeaccelerationZ = 0f;
- private bool isGrounded = false;
- void Move()
- {
- // Move.
- Vector3 forceDirection = new Vector3(
- Input.GetAxis( "Horizontal" ),
- 0f,
- Input.GetAxis( "Vertical" )
- ) * walkAcceleration;
- if( forceDirection != Vector3.zero )
- {
- if( isGrounded ) {
- rigidbody.AddRelativeForce( forceDirection );
- }
- else {
- rigidbody.AddRelativeForce( forceDirection * .1f );
- }
- isMoving = true;
- }
- else
- {
- if( isMoving )
- {
- if( isGrounded )
- {
- walkDeaccelerationX = Mathf.SmoothDamp(
- rigidbody.velocity.x,
- 0f,
- ref ref_walkDeaccelerationX,
- walkDeacceleration );
- walkDeaccelerationZ = Mathf.SmoothDamp(
- rigidbody.velocity.z,
- 0f,
- ref ref_walkDeaccelerationZ,
- walkDeacceleration );
- rigidbody.velocity = new Vector3(
- walkDeaccelerationX,
- rigidbody.velocity.y,
- walkDeaccelerationZ );
- if( rigidbody.velocity.x == 0 && rigidbody.velocity.z == 0 ) {
- isMoving = false;
- }
- }
- }
- }
- // Limit the velocity.
- horizontalMovement = new Vector2( rigidbody.velocity.x, rigidbody.velocity.z );
- if( horizontalMovement.sqrMagnitude > maxWalkSpeed * maxWalkSpeed )
- {
- horizontalMovement = horizontalMovement.normalized * maxWalkSpeed;
- rigidbody.velocity = new Vector3(
- horizontalMovement.x,
- rigidbody.velocity.y,
- horizontalMovement.y );
- }
- }
- void Jump()
- {
- if( Input.GetKeyDown( KeyCode.Space ) && isGrounded )
- {
- rigidbody.velocity = new Vector3(
- rigidbody.velocity.x,
- 0,
- rigidbody.velocity.z );
- }
- }
- void Start() {
- rigidbody.freezeRotation = true;
- }
- void FixedUpdate()
- {
- Move();
- Jump();
- }
- void OnCollisionStay( Collision collisionInfo )
- {
- foreach( ContactPoint contactPoint in collisionInfo.contacts )
- {
- if( Vector3.Angle( contactPoint.normal, Vector3.up ) <= maxSlope )
- {
- isGrounded = true;
- }
- }
- }
- void OnCollisionExit()
- {
- isGrounded = false;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement