- Home /
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
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.
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.