Advertisement
ionroy

2d Car Movement (2d Physics)

Feb 23rd, 2020
203
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.92 KB | None | 0 0
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using UnityEngine;
  5.  
  6. public class CarMovement : MonoBehaviour
  7. {
  8. public static CarMovement Instance;
  9.  
  10. //making public varaible for image
  11. public UnityEngine.UI.Image image;
  12.  
  13. //fuel
  14. public float fuel = 1;
  15.  
  16. //engine burning the fuel
  17. public float fuelconsumption = 0.1f;
  18.  
  19. //Speed for the car will move
  20. public float speed = 1500f;
  21.  
  22. public float rotationSpeed = 15f;
  23.  
  24. //ref to back wheel
  25. public WheelJoint2D backWheel;
  26.  
  27. //ref to front wheel (also this is the Torque)
  28. public WheelJoint2D frontWheel;
  29.  
  30. public Rigidbody2D rb;
  31.  
  32. private float movement = 0f;
  33. private float rotation = 0f;
  34.  
  35. void Awake()
  36. {
  37. Instance = this;
  38. }
  39.  
  40. //This is for user input
  41. void Update()
  42. {
  43. movement = -Input.GetAxisRaw("Vertical") * speed;
  44. rotation = Input.GetAxisRaw("Horizontal");
  45.  
  46. //it counted in frames
  47. image.fillAmount = fuel;
  48. }
  49.  
  50. //This is where we DO the movemnet
  51. void FixedUpdate()
  52. {
  53. // check if the car will be moving
  54.  
  55. //fuel checker
  56.  
  57. if (movement == 0f )
  58. {
  59. backWheel.useMotor = false;
  60. frontWheel.useMotor = false;
  61. }
  62.  
  63. else if(fuel > 0 )
  64. {
  65. Debug.Log("We have fuel");
  66. backWheel.useMotor = true;
  67. frontWheel.useMotor = true;
  68.  
  69. // you can also make it "1000" rather than = "backWheel.motor.maxMotorTorque"
  70. JointMotor2D motor = new JointMotor2D { motorSpeed = movement, maxMotorTorque = backWheel.motor.maxMotorTorque };
  71. backWheel.motor = motor;
  72. frontWheel.motor = motor;
  73. }
  74. rb.AddTorque(-rotation * rotationSpeed * Time.deltaTime);
  75. fuel -= fuelconsumption * Mathf.Abs(movement) * Time.fixedDeltaTime;
  76. }
  77.  
  78. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement