Hi everybody , thanks by advance for your time and help
I have a script for a projectile launcher who work great with a gameobject but i need to change the script to work with all gamobject with a tag “target”.
Here is the script from Projectile Launcher :
using UnityEngine;
using System.Collections;
public enum ProjectileEmissionType
{
EmitWithIntervals = 0,
EmitContinuously,
EmitByCall
}
public enum TargetType
{
Moving = 0,
Static
}
public class ProjectileLauncher : MonoBehaviour {
public GameObject projectilePrefab;
public GameObject player;
public GameObject cannonShotPS;
public ProjectileEmissionType emissionType;
public TargetType targetType;
public float targetRadius;
public float minIntervalBetweenProjectiles;
public float maxIntervalBetweenProjectiles;
public float minIntervalBetweenEmissions;
public float maxIntervalBetweenEmissions;
public int minAmountOfProjectiles;
public int maxAmountOfProjectiles;
public float waitBeforeEmitting;
public float scaleMultiplier;
public LayerMask terrainLayerMask;
public float fTime; //the ideal flight time, of there is no y different between origin and target
public float groundSpeed;
public float slowDownMultiplier; //how much the projectile will slow down
public float slowDownFactor;
private float slowDownInSeconds; //how many seconds the ball will be slow.
private float functionFTime; //the real flight time.
public float gravity;
public bool isACannonBarrel;
public bool shouldPlaySoundForEachCannonBall;
public bool shouldSlowDown;
public bool shootOnPeriphery;
private float playerMovementRadius;// = 35.0f; //***** This is correct for 3 seconds
private AudioSource audioSource;
private Vector3 previousFramePlayerPosition;
private Vector3 previousPlayerPositionForSpeedCheck;
private GameObject cannonBallsParent;
private Quaternion initialbarrelRotation;
// Use this for initialization
void Start ()
{
groundSpeed = 100.0f;
audioSource = gameObject.GetComponent<AudioSource>();
cannonBallsParent = new GameObject();
cannonBallsParent.name = "CannonballsParent";
initialbarrelRotation = transform.rotation;
slowDownFactor *= 0.01f; //from 20% to 0.2 (for example)
//functionFTime = fTime - ( (slowDownMultiplier - 1.0f) * slowDownInSeconds );
previousFramePlayerPosition = player.transform.position;
previousPlayerPositionForSpeedCheck = player.transform.position;
if (targetType == TargetType.Static) //No need to wait for speed calculating
StartCoroutine("ShootProjectiles");
}
// Update is called once per frame
private int frameCount = 0;
private bool shouldStartCoroutine = true;
private Vector3 lastCheckPlayerPosition;
private float timeCounter = 0.0f, rotateSpeed = 2.0f;
/*private Quaternion barrelTargetRotation;
private Quaternion cannonTargetRotation;*/
void Update ()
{
if ( targetType == TargetType.Moving)
{
frameCount++;
timeCounter += Time.deltaTime;
if (frameCount == 10 && shouldStartCoroutine && emissionType != ProjectileEmissionType.EmitByCall)
{
playerMovementRadius = ( (player.transform.position - previousPlayerPositionForSpeedCheck).magnitude) * (1 / timeCounter) * fTime; //5 frames * 6 = 1 second (30 frames)
previousPlayerPositionForSpeedCheck = player.transform.position;
//Debug.Log( (player.transform.position - previousPlayerPositionForSpeedCheck).magnitude);
StartCoroutine("ShootProjectiles");
shouldStartCoroutine = false;
}
if (frameCount == 30)
{
playerMovementRadius = ( (player.transform.position - previousPlayerPositionForSpeedCheck).magnitude) * (1 / timeCounter) * fTime; //30 frames is approximately 1 second
previousPlayerPositionForSpeedCheck = player.transform.position;
//Debug.Log("PlayerMovementRadius" + playerMovementRadius + "FrameCount = " + frameCount);
frameCount = 0;
timeCounter= 0.0f;
}
}
}
void OnDestroy()
{
StopCoroutine("ShootProjectiles");
}
IEnumerator ShootProjectiles()
{
//Shoot three cannons, one from the middle of the ship and the other 2 at +- 10 units on the X axis.
//x = vt +at^2/2
//Vy = v0 + at
//radious = 35 units
//time = 3 seconds
yield return new WaitForSeconds (waitBeforeEmitting);
float random;
Vector3 playerVelocity, perpendicularVector, playerPosition;
Vector3 randomPointOnRadius, randomTargetPoint;
Vector3 initialFlightVelocity, direction;
float initialYVelocity, flightDistance, oldAngle = 0.0f, currentAngle;
bool isFirstTime = true;
while (true)
{
int amountOfProjectiles = Random.Range(minAmountOfProjectiles, maxAmountOfProjectiles);
int xOffset = (-(amountOfProjectiles - 1)/2) * 10;
if (emissionType == ProjectileEmissionType.EmitContinuously)
{
shouldPlaySoundForEachCannonBall = true;
audio.volume = 0.1f;
}
else
{
if (!shouldPlaySoundForEachCannonBall)
{
audioSource.volume = 0.5f;
audioSource.PlayOneShot(audioSource.clip);
}
else audio.volume = 0.5f / amountOfProjectiles;
}
for (int j = 0; j < amountOfProjectiles; j++)
{
playerPosition = player.transform.position;
if (targetType == TargetType.Moving)
{
playerVelocity = playerPosition - previousFramePlayerPosition; //direction
previousFramePlayerPosition = playerPosition;
perpendicularVector = new Vector3(-playerVelocity.z, playerVelocity.x, playerVelocity.y);
random = Random.Range(-playerMovementRadius/2, playerMovementRadius/2);
if (playerVelocity != Vector3.zero)
{
randomPointOnRadius = playerPosition + random * perpendicularVector.normalized;
randomTargetPoint = randomPointOnRadius + playerVelocity.normalized * Random.Range( playerMovementRadius, playerMovementRadius * 1.3f );
}
else
randomTargetPoint = playerPosition + new Vector3(random, 0.0f, random);
}
else {
Vector3 randomDirection = new Vector3(Random.Range(-1.0f, 1.0f), 0.0f, Random.Range(-1.0f, 1.0f) );
if (shootOnPeriphery)
randomTargetPoint = playerPosition + randomDirection.normalized * targetRadius;
else randomTargetPoint = playerPosition + randomDirection * targetRadius;
}
randomTargetPoint.y = ProjectileLauncherHelper.SampleLayerHeight(randomTargetPoint, terrainLayerMask);
//Debug.Log("Target Y position = " + randomTargetPoint.y);
if (randomTargetPoint.y <= 0.0f) //the ball will fall where there is no terrain
continue;
direction = randomTargetPoint - transform.position; // get target direction
//direction.y = 0; // retain only the horizontal direction
flightDistance = direction.magnitude; // get horizontal distance
fTime = flightDistance / groundSpeed;
if (fTime < 0.4f) //The user is too close to the cannon
fTime = 0.4f;
//Parameters
float t1 = fTime / 2.0f; //Highest point, approximately
//float height = flightDistance / 2.0f;
//
//Gravity set, no drag
float v0y = gravity * t1;
float height = v0y * t1 - gravity * t1 * t1 / 2.0f;
float highestPoint = transform.position.y + height;
float t2 = Mathf.Sqrt(2.0f * (highestPoint - randomTargetPoint.y) / gravity );
if ( float.IsNaN(t2) )
{
t2 = t1;
//Debug.LogError("NaN value");
}
float fullTime = t1 + t2;
float vx = flightDistance / fullTime;
//functionFTime = fullTime - ( (slowDownMultiplier - 1.0f) * slowDownInSeconds );
//Debug.Log("v0y: " + v0y + "; vx: " + vx + "; gravity: " + gravity + "; t1: " + t1 + "; t2: " + t2 + "; fullTime: " + fullTime + "; height: " + height);
initialFlightVelocity = new Vector3(direction.normalized.x * vx, v0y, direction.normalized.z * vx);
Debug.Log(t2);
float timeScale1 = 0.0f, timeScale2 = 0.0f;
if (isACannonBarrel)//rotation the cannon and the barrel
{
//direction = player.transform.position - transform.position;
direction.y = 0;
if (isFirstTime)
{
rotateSpeed = 2.0f;
isFirstTime = false;
}
else rotateSpeed = 5.0f;
//currentAngle = Mathf.Rad2Deg * Mathf.Atan(height / (flightDistance / 2) );
currentAngle = Vector3.Angle(direction, initialFlightVelocity);
float rate = 1.0f / rotateSpeed;
//timeScale1 = 0.0f;
Quaternion q = transform.parent.rotation;
while(timeScale1 < rate)
{
timeScale1 += Time.deltaTime;
transform.parent.rotation = Quaternion.Slerp(q, Quaternion.LookRotation(direction), timeScale1/rate);
//print(timeScale);
yield return new WaitForEndOfFrame();
}
//timeScale2 = 0.0f;
q = transform.rotation;
while(timeScale2 < rate)
{
timeScale2 += Time.deltaTime;
transform.rotation = Quaternion.Slerp(q, q * Quaternion.Euler(oldAngle - currentAngle, 0.0f, 0.0f), timeScale2/rate);
//print(timeScale);
yield return new WaitForEndOfFrame();
}
oldAngle = currentAngle;
//Debug.Log("Angle = " + oldAngle);
//Debug.Log(new Quaternion(0.0f, q.y, q.z, q.w) * Quaternion.Euler(-angle, 0.0f, 0.0f));
}
GameObject projectile, ps;
projectile = Object.Instantiate(projectilePrefab, new Vector3(transform.position.x/* + xOffset*/, transform.position.y, transform.position.z), Quaternion.identity ) as GameObject;
projectile.transform.parent = cannonBallsParent.transform;
projectile.transform.localScale *= scaleMultiplier;
slowDownInSeconds = slowDownFactor * fTime;
Projectile tempProjectile = projectile.GetComponent<Projectile>();
tempProjectile.SetParameters(terrainLayerMask, gravity, initialFlightVelocity, player, randomTargetPoint, fTime, slowDownMultiplier, slowDownInSeconds);
ps = Object.Instantiate(cannonShotPS, transform.position, Quaternion.identity) as GameObject;
ps.gameObject.transform.parent = gameObject.transform;
//ps.gameObject.transform.position = Vector3.zero;
ps.gameObject.transform.rotation = transform.rotation;
//ps.gameObject.transform.position = new Vector3(transform.position.x, transform.position.y, transform.position.z - 12.0f);
xOffset += 10;
if (shouldPlaySoundForEachCannonBall)
audioSource.PlayOneShot(audioSource.clip);//Messenger.Broadcast<AudioSource>("play sound with audiosource", audioSource);
float randomInterval = Random.Range(minIntervalBetweenProjectiles, maxIntervalBetweenProjectiles);
if (!isACannonBarrel)
yield return new WaitForSeconds (randomInterval);
else if (timeScale1 + timeScale2 < randomInterval)
yield return new WaitForSeconds (randomInterval - (timeScale1 + timeScale2) );
}
if (emissionType == ProjectileEmissionType.EmitByCall)
break;
if (emissionType == ProjectileEmissionType.EmitWithIntervals)
yield return new WaitForSeconds(Random.Range(minIntervalBetweenEmissions, maxIntervalBetweenEmissions) );
}
}
void Reset()
{
scaleMultiplier = 1.0f;
gravity = 100.0f;
groundSpeed = 100.0f; //100 units per second
fTime = 3.0f;
shouldSlowDown = true;
slowDownFactor = 15f;
waitBeforeEmitting = 0.1f;
minIntervalBetweenProjectiles = 0.1f;
maxIntervalBetweenProjectiles = 0.15f;
minIntervalBetweenEmissions = 5.0f;
maxIntervalBetweenEmissions = 7.0f;
minAmountOfProjectiles = 5;
maxAmountOfProjectiles = 7;
emissionType = ProjectileEmissionType.EmitWithIntervals;
targetType = TargetType.Static;
targetRadius = 20.0f;
shouldSlowDown = true;
slowDownMultiplier = 2.0f;
slowDownFactor = 15.0f;
shouldPlaySoundForEachCannonBall = false;
isACannonBarrel = false;
shootOnPeriphery = true;
}
public void Fire()
{
StartCoroutine("ShootProjectiles");
}
}
As you can see , we can define a gameObject but not all gameobject with a tag “target”
and the second problem is if the gameobject is destroyed that return an error on unity .
Please help me i’m a newbie
Thanks a lot .
Malakdecaen.