Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 12 Next capture
2021 2022 2023
1 capture
12 Jun 22 - 12 Jun 22
sparklines
Close Help
  • 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 Xenon42 · Sep 15, 2016 at 12:23 AM · controlaccelerationforcesspeed issues

Building a speed limit and deceleration system, need help fixing/optimising

I'm trying to make a spaceship dogfighting game, and have been trying to make my ships move like airplanes - always moving forward and cancelling sideways momentum, cancelling angular momentum when none of the pitch, roll or yaw keys are held down, and so on.

I've got a pair of scripts at the moment that are reasonably functional, one to control my test ship's orientation, and one to control its movement. Currently I want to rewrite the movement code to do a bunch of things:

  • I want the player to be able to increase or decrease the top speed (up to a set limit), whereupon the ship will accelerate to that speed, then stop accelerating and hold to its current forward velocity.

  • If the ship changes direction, I want it to re-accelerate until it's back up to full speed again. If the player reduces the ship's top speed, I want the ship to decelerate to match it.

  • I also want it to be possible to make the ship stop entirely, and go into reverse, with the same rules as going forwards.

Unfortunately, my current script is a broken mess, and I don't know what's going wrong. The ship will only move forward at a very limited rate, will accelerate backwards indefinitely, and if I alter the ship's orientation while moving it starts accelerating out of control in seemingly random directions.

I would greatly appreciate it if someone could review my script and point out any problems they can see, or offer any pointers on how my code could be made more efficient (I'm sure what I've got right now is very messy). I know that's quite a lot to ask, but I'm seriously struggling to untangle this stuff myself.

Here's my script:

 using UnityEngine;
 using System.Collections;
 
 public class Thrust : MonoBehaviour
 {
     public float accelRate;
     public float maxSpeed;
     public Rigidbody rb;
     float speed;
     float reverseSpeed;
     int throttle;
     int reverseThrottle;
     int speedKeyState;
 
     void Start () 
     {
         rb = GetComponent<Rigidbody>();
         speed = 0f;
         throttle = 0;
         reverseSpeed = 0f;
         reverseThrottle = 0;
         speedKeyState = 0;
         Vector3 localVel = rb.transform.InverseTransformDirection (GetComponent<Rigidbody> ().velocity);
         localVel.z = maxSpeed;
     }
 
     void FixedUpdate ()
     {
         Vector3 localVel = rb.transform.InverseTransformDirection (GetComponent<Rigidbody> ().velocity);
 
         //This thrust is applied constantly, but limited by the state of the throttle variables
         rb.AddRelativeForce (Vector3.forward * (throttle * (accelRate * Time.deltaTime)));
         rb.AddRelativeForce (Vector3.back * (reverseThrottle * (accelRate * Time.deltaTime)));
 
 
         //These two if blocks are meant to stop the ship from accelerating beyond the max speed, forwards or backwards, and apply a decelerating force in either direction to bring the ship back to the limit
         if (localVel.z >= maxSpeed * speed) {
             if (speed != 0) {
                 throttle = 0;
                 rb.AddRelativeForce (Vector3.back * ((accelRate * Time.deltaTime) * 0.1f));
             }
                 throttle = 0;
         } else {
             throttle = 1;
         }
 
 
         if (localVel.z <= -(maxSpeed * reverseSpeed)) {
             if (reverseSpeed != 0) {
                 reverseThrottle = 0;
                 rb.AddRelativeForce (Vector3.back * ((accelRate * Time.deltaTime) * 0.1f));
             }
             reverseThrottle = 0;
         } else {
             reverseThrottle = 1;
         }
 
         //These if blocks are intended to cancel out momentum on all axes besides Z, so the ship doesn't end up drifting sideways while flying
         if (localVel.x > 0f)
         {
             rb.AddRelativeForce (Vector3.left * (speed * ((accelRate * 2) * Time.deltaTime)));
             rb.AddRelativeForce (Vector3.left * (reverseSpeed * ((accelRate * 2) * Time.deltaTime)));
         }
         if (localVel.x < 0f)
         {
             rb.AddRelativeForce (Vector3.right * (speed * ((accelRate * 2) * Time.deltaTime)));
             rb.AddRelativeForce (Vector3.right * (reverseSpeed * ((accelRate * 2) * Time.deltaTime)));
         }
         if (localVel.y > 0f)
         {
             rb.AddRelativeForce (Vector3.down * (speed * ((accelRate * 2) * Time.deltaTime)));
             rb.AddRelativeForce (Vector3.down * (reverseSpeed * ((accelRate * 2) * Time.deltaTime)));
         }
         if (localVel.y < 0f)
         {
             rb.AddRelativeForce (Vector3.up * (speed * ((accelRate * 2) * Time.deltaTime)));
             rb.AddRelativeForce (Vector3.up * (reverseSpeed * ((accelRate * 2) * Time.deltaTime)));
         }
 
         //This if block and the switch below are the controls that allow the player to increase or decrease the top speed, or go into reverse
         if (Input.GetKey (KeyCode.UpArrow))
             speedKeyState = 1;
         if (Input.GetKey (KeyCode.DownArrow))
             speedKeyState = 2;
         if (!Input.GetKey (KeyCode.UpArrow) && !Input.GetKey (KeyCode.DownArrow))
             speedKeyState = 0;
 
         switch (speedKeyState)
         {
         case 1:
             speed += 0.01f;
             break;
         case 2:
             if (speed == 0f)
                 reverseSpeed += 0.01f;
             else
                 speed -= 0.01f;
             break;
         case 0:
             if (reverseSpeed > 0f)
                 reverseSpeed -= 0.01f;
             break;
         }
 
         //These if blocks ensure that the speed variables cannot rise or fall below certain thresholds, so that the ship will always be limited to 100% top speed going forwards, and 20% top speed going backwards
         if (speed > 1f)
             speed = 1f;
         if (speed < 0f)
             speed = 0f;
 
         if (reverseSpeed > 0.2f)
             reverseSpeed = 0.2f;
         if (reverseSpeed < 0f)
             reverseSpeed = 0f;
     
         //Some print functions for debug purposes
         print ("speed is: " + speed);
         print ("throttle is: " + throttle);
         print ("localVel is: " + localVel);
         print ("reverseThrottle is: " + reverseThrottle);
         print ("reverseSpeed is: " + reverseSpeed);
     }
 }
Comment
Add comment
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

0 Replies

· Add your reply
  • Sort: 

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.

Follow this Question

Answers Answers and Comments

52 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

Related Questions

How to make camera position relative to a specific target. 1 Answer

Recalibrated 'zero' point for Input.acceleration messes up when goes to upside-down 0 Answers

Disable movement control during jump 3 Answers

Obtaining Constant Speed with AddForce 1 Answer

take control over particles 0 Answers


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