Advertisement
Baserfaz

Car physics 2d top down - unity 5

Aug 27th, 2015
855
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.77 KB | None | 0 0
  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class car : MonoBehaviour {
  5.  
  6.     private float speed = 0f;
  7.     private float maxSpeed = 15f;
  8.     private float startAngluraDrag;
  9.     private float startOrthoSize;
  10.  
  11.  
  12.     void Start () {
  13.         startOrthoSize = Camera.main.orthographicSize;
  14.         startAngluraDrag = GetComponent<Rigidbody2D> ().angularDrag;
  15.     }
  16.  
  17.     void FixedUpdate () {
  18.         CameraFunctions ();
  19.         InputHandlingKB ();
  20.         MovementHandlersRigid ();
  21.     }
  22.  
  23.     //using rigidbody2d
  24.     private void MovementHandlersRigid() {
  25.         GetComponent<Rigidbody2D> ().AddForce (transform.right * speed);
  26.         if (GetComponent<Rigidbody2D> ().velocity.magnitude > 0.5f) {
  27.             GetComponent<Rigidbody2D> ().angularDrag = startAngluraDrag;
  28.             GetComponent<Rigidbody2D> ().AddTorque (-Input.GetAxisRaw ("Horizontal"));
  29.         } else {
  30.             GetComponent<Rigidbody2D> ().angularDrag = 10f;
  31.         }
  32.     }
  33.  
  34.     //keyboard && gamepad
  35.     private void InputHandlingKB() {
  36.         if (Input.GetKey (KeyCode.UpArrow) || Input.GetAxisRaw ("Fire2") > 0f) {
  37.             if (speed < maxSpeed) {
  38.                 speed += 0.1f;
  39.             }
  40.         } else if (Input.GetKey (KeyCode.DownArrow) || Input.GetAxisRaw ("Fire3") > 0f) {
  41.             if (speed > 0f) {
  42.                 speed -= 0.3f;
  43.             }
  44.         } else {
  45.             if (speed > 0f) {
  46.                 speed -= 0.2f;
  47.             }
  48.         }
  49.         if (speed < 0f) {
  50.             speed = 0f;
  51.         }
  52.     }
  53.  
  54.     //camera follow, smooth
  55.     private void CameraFunctions() {
  56.         if (speed > startOrthoSize) {
  57.             Camera.main.orthographicSize = Mathf.Lerp (Camera.main.orthographicSize, 5f, Time.deltaTime * 0.5f);
  58.         } else {
  59.             Camera.main.orthographicSize = Mathf.Lerp (Camera.main.orthographicSize, startOrthoSize, Time.deltaTime * 0.5f);
  60.         }
  61.         Camera.main.transform.position -= (Camera.main.transform.position - new Vector3(transform.position.x, transform.position.y, -10f)) * Time.deltaTime * 10f;
  62.     }
  63. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement