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 tbr · Dec 20, 2018 at 05:36 PM · scripting problemmissile

Unity Missile Script - randomly a missile spirals out of control

I have a homing missile script that seems to work 99% of the time, but every so often one of the missiles will start spiralling out of control and not towards the player. I can't see any reason for it, I can't see a reason for the behaviour in the code and I'm after a pair of fresh eye's to take a look and see if I'm missing something obvious.

 using System.Collections;
 using System.Collections.Generic;
 using UnityEngine;
 using System.Linq;
 
     public class missileControl : MonoBehaviour
     {
         public Transform missileTarget;
 
         public GameObject indicator;
 
         private int scorePerHit = 1;
         private int scorePerDestroy = 50;
         private int hits = 1;
 
         [Header("Enemy Culling Variables")]
         [HideInInspector]
         public float distanceToCull = 4f;
         [HideInInspector]
         private Transform spaceShip;
 
         public Rigidbody missileRigidbody;
 
         [Header("Missile Control Variables")]
         public float turn = 0.9f;
         private float initialTurn = 0.9f;
         public float missileVelocity = 95f;
         private float initialMissileVelocity = 95f;
         private Vector3 resetMissileVelocity = new Vector3(0f,0f,0f);
 
         private Transform myTransform;
         private float wiggleMultiplyer = 40f;
 
         [Header("Firing Audio")]
         public float minPitch = 0.9f;
         public float maxPitch = 1f;
         public AudioClip indicatorClip;
         public TrailRenderer trailRenderer;
 
         private bool indicatorOff = true;
         private float currentDistance = 100f;
         public float indicatorDist = 300f;
 
 
         private IEnumerator delayAimTimer;
 
         private void Start()
         {
             spaceShip = LevelVariables.currentLevelVariables.spaceShip.transform; // Player to test if behind
             missileTarget = LevelVariables.currentLevelVariables.playerTarget.transform; // Target
             missileRigidbody.velocity = resetMissileVelocity;
 
             ResetVariables();
         }
 
         private void OnEnable()
         {
             ResetVariables();
         }
 
         private void OnDisable()
         {
             missileRigidbody.velocity = resetMissileVelocity;
         }
 
         void ResetVariables()
         {
             trailRenderer.enabled = false;
             StartCoroutine(DelayTrails());
 
             indicatorOff = true;
 
             turn = Random.Range(initialTurn * 0.85f, initialTurn * 1.15f);
             wiggleMultiplyer = Random.Range(0 - (wiggleMultiplyer), wiggleMultiplyer);
 
             missileRigidbody.velocity = resetMissileVelocity;
             missileVelocity = Random.Range(initialMissileVelocity * 0.85f, initialMissileVelocity * 1.15f);
             missileRigidbody.velocity = transform.forward * missileVelocity;
         }
 
         IEnumerator DelayTrails()
         {
             yield return new WaitForSeconds(0.15f);
             trailRenderer.Clear();
             trailRenderer.enabled = true;
         }
 
         private void FixedUpdate()
         {
             if (GameStateController.gameStateController.gameState == GameStateController.GameState.PLAYERSTART)
             {
                 if (Vector3.Angle((gameObject.transform.position - spaceShip.position), spaceShip.transform.forward) > 90)
                 {
                     if ((gameObject.transform.position - spaceShip.position).sqrMagnitude > distanceToCull * distanceToCull)
                     {
                         KillEnemy();
                         return;
                     }
                 }
                 else
                 {
                     if (indicatorOff)
                     {
                         currentDistance = Vector3.Distance(missileTarget.position, transform.position);
                         if (currentDistance <= indicatorDist)
                         {
                             indicator.SetActive(true);
                             PlayAudioSound(indicatorClip);
                             indicatorOff = false;
                         }
                     }
 
                     //missileRigidbody.velocity = (transform.forward * missileVelocity) + (transform.right * (Mathf.Sin(Time.time) * wiggleMultiplyer)) + (transform.up * (Mathf.Cos(Time.time) * wiggleMultiplyer));
 
                     missileRigidbody.velocity = transform.forward * missileVelocity;
                     var rocketTargetRotation = Quaternion.LookRotation(missileTarget.position - transform.position);
                     missileRigidbody.MoveRotation(Quaternion.RotateTowards(transform.rotation, rocketTargetRotation, turn));
                 }
             }
             else
             {
                 StartCoroutine(DestroyGameObject(gameObject, 0f));
             }          
         }
 
 
         void OnCollisionEnter(Collision hit)
         {
             switch (hit.gameObject.tag)
             {
                 case "environment":
                     KillEnemy();
                     break;
                 case "enemy":
                     KillEnemy();
                     break;
                 case "enemyBullet":
                     break;
                 case "player":
                     CameraShake.Shake(1f, 0.25f);
 
                     float deathScale = Random.Range(5f * transform.localScale.x, 10f * transform.localScale.x);
                     GameObject fx = ObjectPooler.currentPool.enemyHits.Spawn();
 
                     if (fx == null) return;
 
                     fx.transform.position = transform.position;
                     fx.transform.rotation = Quaternion.identity;
                     fx.transform.parent = hit.transform;
                     fx.transform.localScale = new Vector3(deathScale, deathScale, deathScale);
                     fx.SetActive(true);
 
                     KillEnemy();
                     break;
                 case "playerBullet":
                     ProcessHit();
 
                     if (hits < 1)
                     {
                         LevelVariables.currentLevelVariables.scoreBoard.ScoreHit(scorePerDestroy);
                         KillEnemy();
                     }
                     break;
             }
         }
 
         private void ProcessHit()
         {
             LevelVariables.currentLevelVariables.scoreBoard.ScoreHit(scorePerHit);
             hits = hits - 1;
         }
 
         private void KillEnemy()
         {
             GameObject fx = ObjectPooler.currentPool.enemyDeath.Spawn();
 
             if (fx == null) return;
 
             fx.transform.position = transform.position;
             fx.transform.rotation = Quaternion.identity;
             fx.transform.parent = LevelVariables.currentLevelVariables.spawnParent;
 
             float deathScale = 1f;
             deathScale = Random.Range(1f * transform.localScale.x, 4f * transform.localScale.x);
 
             fx.transform.localScale = new Vector3(deathScale, deathScale, deathScale);
             fx.SetActive(true);
 
             StartCoroutine(DestroyGameObject(gameObject, 0f));
         }
 
         public void PlayAudioSound(AudioClip clip)
         {
             LevelVariables.currentLevelVariables.computerAudioSource.volume = 1f;
             LevelVariables.currentLevelVariables.computerAudioSource.PlayOneShot(clip);
         }
 
         IEnumerator DestroyGameObject(GameObject turnOffObject, float waitTime)
         {
             yield return new WaitForSeconds(waitTime);
             trailRenderer.Clear();
             trailRenderer.enabled = false;
             turnOffObject.Recycle();
         }
 
     }

The code for creating the missile is below

 GameObject missileObj = ObjectPooler.currentPool.destroyerMissileAmmo.Spawn();
 
                 if (missileObj == null) yield break;
 
                 CreateMuzzleFlash(muzzleLocation);
 
                 //LevelVariables.currentLevelVariables.globalMissileAmount = LevelVariables.currentLevelVariables.globalMissileAmount + 1;
                 missileObj.transform.localScale = new Vector3(2f, 2f, 2f);
                 missileObj.transform.position = muzzleLocation.transform.position;
                 missileObj.transform.rotation = muzzleLocation.transform.rotation;
 
                 //missileObj.transform.LookAt(m_target.transform);
                 missileObj.SetActive(true);

I don't see any problems with this code that would cause a missile not to head towards the player, does anyone have any idea's

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

2 Replies

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

Answer by tbr · Dec 21, 2018 at 02:38 PM

I finally figured it out after eliminating all possibilities.... I found that I wasn't correctly resetting the velocity of the missiles, I had to reset the angular velocity as well as just the velocity.

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
avatar image
0

Answer by LCStark · Dec 20, 2018 at 07:40 PM

The nested if statements make it pretty difficult to analyze quickly, and Unity Answers' terrible code formatting doesn't help. You might want to re-think your code structure a bit.

Look at this example function:

void Abc()
{
  if (x)
  {
    if (y)
    {
      if(z)
      {
        // do x + y + z
      }
      else
      {
        // do x + y + !z
      }
    }
    else
    {
      // do x + !y
    }
  }
  else
  {
    // do !x
  }
}
It's easy to get lost in these braces already. If you plan to build up on that code, it will only make things more difficult to debug. You could move the code in braces to separate functions, but in this case I don't think a lot of smaller functions will work much better. You could, however, take advantage of the ability to return from a function whenever you want to make your code more readable:
void Abc()
{
  if (!x)
  {
    // do !x
    return;
  }

if (!y) { // do x + !y return; }
if (z) { // do x + y + z } else { // do x + y + !z } }


As for your problem: you say that your missiles sometimes spiral out of control. Could the rotation code be the source of the problem? Try putting some Debug.Log's in there and check if the LookRotation returns expected movement direction (do something like Debug.Log(rotation * Vector3.forward) to see the direction your rotation is moving you to).

Edit
When debugging rotations and directions, Debug.DrawRay can be very useful to see if something isn't pointing in the right direction. By default, they'll only be visible in the Scene tab. You can press the Gizmos button to also see them on the Game tab.
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.

Follow this Question

Answers Answers and Comments

169 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 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 avatar image avatar image avatar image

Related Questions

How can I slowly rotate a vector2 to track a target and give velocity based on the angle. 1 Answer

lock turret rotation to local Y 2 Answers

Rotate object around another object C# 2 Answers

Problems with instantiate 0 Answers

How to measure the height of a stack of objects? 2 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