• Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
0
Question by eneskan13_unity · Jun 10, 2018 at 11:59 PM · car

2d Car nitro boost

How to write c# code 2d Car nitro , boost ?

Comment
Add comment · Show 2
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image xorap · Jun 11, 2018 at 12:01 AM 0
Share

Can you provide the script that controls the movement of the 2D car?

avatar image eneskan13_unity xorap · Jun 11, 2018 at 12:06 AM 0
Share

using UnityEngine;
using System.Collections;

public class CarController : $$anonymous$$onoBehaviour {

 Rigidbody2D rb;
 // Car rigidbody CO$$anonymous$$
 public Transform centerOf$$anonymous$$ass;

 // Wheel motor for drive the car based on wheelJoint 2D
 Joint$$anonymous$$otor2D motorBack;  

 // Which wheel to drive with that?
 public WheelJoint2D motorWheel;

 // Store car speed
 public float speed ;   

 // Store is grounded based on the distance of the ground
 bool isGrounded;

 // How much distance of the ground means cars is grounded? answer=> less than 2.1f
 public float groundDistance = 2.1f ;

 // $$anonymous$$otor power, Brake power and deceleration speed
 public float motorPower = 14000f,
 brakePower = -14f,
  decelerationSpeed = 0.3f;

 // Car max speed
 public float maxSpeed = 14f;

 public bool NOS = false;
 private bool NOSActivation = false;
 public float BoostPercentage = 50.0f;
 public float NOSQuantity = 5.0f;



 // inrenal usage
 float motorTemp;

 // Can rotate option. be true value when car is on the fly
 bool canRotate = false;

 // Rotate force on the  fly 
 public float RotateForce = 140f;

 [HideInInspector]public AudioSource EngineSoundS;

 public bool is$$anonymous$$obile;

 public ParticleSystem wheelParticle;

 // Internal usage
 float powerTemp;
 ParticleSystem.Emission$$anonymous$$odule em ,emSmoke;

 public Transform particlePosition;


 public bool useSmoke;
 public ParticleSystem smoke;
 public float smokeTargetSpeed = 17f;

 public float cameraDistance = 15f;


 void Awake()
 {
     Vector3 posCamera;
     posCamera = Camera.main.transform.position;
     Camera.main.transform.position = new Vector3 (posCamera.x, posCamera.y, - cameraDistance);
 }

2 Replies

· Add your reply
  • Sort: 
avatar image
0
Best Answer

Answer by eneskan13_unity · Jun 11, 2018 at 12:07 AM

void Start () {

     rb = this.GetComponent<Rigidbody2D>();
    

     // Set car rigidbody's COM
     GetComponent<Rigidbody2D>().centerOfMass = centerOfMass.transform.localPosition;

     // Starting with WheelJoint2D motor
     motorBack = motorWheel.motor; 

     // Cast a ray to find isGrounded 
     StartCoroutine (RaycCast ());

     EngineSoundS = GetComponent<AudioSource> ();

     powerTemp = motorPower;

     em = wheelParticle.emission;
     em.enabled = false;

     if (smoke) {
         emSmoke = smoke.emission;
         emSmoke.enabled = false;
     }



 }  

 float currentSpeed;    
 //float maxspeed = 300f;

 void FixedUpdate(){

     // speed limiter based on max speed limit value
     if (speed > maxSpeed)
         motorPower = 0;
     else
         motorPower = powerTemp;
     
     // Moving forward
     if (Input.GetAxis ("Horizontal") > 0 || HoriTemp > 0) {

         // Add force to car back wheel
         if(isGrounded)
             motorBack.motorSpeed = Mathf.Lerp (motorBack.motorSpeed, -motorPower, Time.deltaTime * 1.4f);

         // Wheel particles
         if (isGrounded) {
             if (speed < 4.3f) {
                 wheelParticle.transform.position = particlePosition.position;

                 em.enabled = true;

             } else
                 em.enabled = false;
         }
         else
             em.enabled = false;
         
     }
     else 
     {// Moving backward
         if (Input.GetAxis ("Horizontal") < 0 || HoriTemp < 0) {
             if (speed < -maxSpeed) {
                 if (isGrounded)
                     motorBack.motorSpeed = Mathf.Lerp (motorBack.motorSpeed, 0, Time.deltaTime * 3f);
             } else {
                 if (isGrounded)
                     motorBack.motorSpeed = Mathf.Lerp (motorBack.motorSpeed, motorPower, Time.deltaTime * 1.4f);
             }
                                                                                   
         } else {// Releasing car throttle and brake
             if (isGrounded)
                 motorBack.motorSpeed = Mathf.Lerp (motorBack.motorSpeed, 0, Time.deltaTime * decelerationSpeed);    
         }

     }

     // Update WheelJoint2D motor inputs

     motorWheel.motor = motorBack; 

     // Cheack fo rotate on the fly
 
     Rotate ();
 
     #if UNITY_EDITOR
     EngineSoundEditor ();  
     #else
     EngineSoundMobile (); 
     #endif

     if (!isMobile)
         HoriTemp = Input.GetAxis ("Horizontal");

     if (useSmoke) {
         if (Input.GetAxis ("Horizontal") > 0 || HoriTemp > 0) {
             if (speed < smokeTargetSpeed)
                 emSmoke.enabled = true;
             else
                 emSmoke.enabled = false;
         } else
             emSmoke.enabled = false;
     }
 }
Comment
Add comment · Show 1 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image eneskan13_unity · Jun 11, 2018 at 12:08 AM 0
Share
 void LateUpdate()
 {

     // Get car speed
     speed = GetComponent<Rigidbody2D>().velocity.magnitude;
     if (Input.GetAxis ("Horizontal") < 0 || HoriTemp < 0) 
         speed = -speed;
 }

 // Rotate car on air based on speed
 void Rotate()
 {
     //based on player forward input(Like Hill Climb Racing game)
     if (Input.GetAxis ("Horizontal") > 0 || HoriTemp > 0) {


         GetComponent<Rigidbody2D> ().AddTorque (RotateForce);
     } else {

         if (Input.GetAxis ("Horizontal") < 0.0f || HoriTemp < 0)
             GetComponent<Rigidbody2D> ().AddTorque (-RotateForce);

         AnalougeSpeedConverter.ShowSpeed(rb.velocity.magnitude, 0, 30);
     }
 }

 // Raycast body to find that car is on the ground or not
 IEnumerator RaycCast()
 {

     while (true) 
     {
         
         yield return new WaitForEndOfFrame();

         RaycastHit2D hit = Physics2D.Raycast (transform.position, -Vector2.up, 1000);

         float distance = $$anonymous$$athf.Abs(hit.point.y - transform.position.y);


         if (distance < groundDistance)
             isGrounded = true;
         else
             isGrounded = false;

         canRotate = !isGrounded;      

     }

 }

 // Engine sound system

 public float $$anonymous$$ultiplyer = 3f;
 public float $$anonymous$$P = 1f;
 public float maxP = 2.4f;
 float HoriTemp;

 public void  EngineSound$$anonymous$$in ()
 {
     if (EngineSoundS.pitch > $$anonymous$$P)
         EngineSoundS.pitch -= 1.4f * Time.deltaTime;
 }

 public void EngineSound$$anonymous$$obile ()
 {
     
     if (speed < 40) 
     {
         EngineSoundS.pitch = $$anonymous$$athf.Lerp (EngineSoundS.pitch, $$anonymous$$athf.Clamp (HoriTemp * $$anonymous$$ultiplyer, $$anonymous$$P, maxP), Time.deltaTime * 5);
     } 
     else 
     {
         EngineSoundS.pitch = $$anonymous$$athf.Lerp (EngineSoundS.pitch, $$anonymous$$athf.Clamp (HoriTemp * $$anonymous$$ultiplyer, $$anonymous$$P, maxP), Time.deltaTime * 5);
     }
 }

 public void EngineSoundEditor ()
 {

     if (speed < 40) 
     {
         EngineSoundS.pitch = $$anonymous$$athf.Lerp (EngineSoundS.pitch, $$anonymous$$athf.Clamp (Input.GetAxis ("Horizontal") * $$anonymous$$ultiplyer, $$anonymous$$P, maxP), Time.deltaTime * 5);
     } 
     else 
     {
         EngineSoundS.pitch = $$anonymous$$athf.Lerp (EngineSoundS.pitch, $$anonymous$$athf.Clamp (Input.GetAxis ("Horizontal") * $$anonymous$$ultiplyer, $$anonymous$$P, maxP), Time.deltaTime * 5);
     }
 }


   

 // Vehicle input system
 //this is public function for car Acceleration UI Button
 public void Acceleration ()
 {
     HoriTemp = 1f;
 }


 public void Nitro()
 {
     HoriTemp = 10f;
 }



 //this is public function for car Brake\Backward UI Button
 public void Brake ()
 {
     HoriTemp = -1f;
 }


 //this is for when player both release Brake or Acceleration button
 public void GasBrakeRelease ()
 {

     HoriTemp = 0;


 }

}

avatar image
0

Answer by xorap · Jun 11, 2018 at 12:33 AM

Using the script you've provided, I would add a nitro input through Edit>ProjectSettings> Input, then either replacing one of the existing axes or adding another. Name it accordingly, and with the correct settings. Next, within the above code, insert public float newMax; public float nitroPower; public float nitroBoostRate, and a coroutine for the nitroboost IEnumerator nitroBoost();, one that detects input from the key you chose, for instance while(Input.GetKeyDown("Nitro") { maxSpeed = newMax; motorPower = Mathf.Lerp ( 14000, nitroPower, nitroBoostRate); yield return null; }

Then I would add a nitro deceleration rate public float nitroDecelRateand do the same as before, for the key up after closing the while() within nitroBoost()like so: else{ if(Input.GetKeyUp("Nitro")) {maxSpeed = mathf.Lerp( newMax, 14f, nitroDecelRate); motorPower = Mathf.Lerp ( motorPower, 14000f, nitroDecelRate); } Finally, you may consider adding an additional float for the nitroPowerDecelfor added adjustment.

This is all considering there isn't already a method and input key for NOS somewhere in the rest of your script, as there is a bool NOS = false and bool NOSActivation.

Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Welcome to Unity Answers

If you’re new to Unity Answers, please check our User Guide to help you navigate through our website and refer to our FAQ for more information.

Before posting, make sure to check out our Knowledge Base for commonly asked Unity questions.

Check our Moderator Guidelines if you’re a new moderator and want to work together in an effort to improve Unity Answers and support our users.

Follow this Question

Answers Answers and Comments

83 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

Vehicle AI Pathfinding Trouble 0 Answers

Why my car fall over when I turn left or right?? 0 Answers

my car loses power over time? : o 0 Answers

Car steering issue 0 Answers

Collision Car Sensors 1 Answer


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges