Automatic grid movement - c#

I would like to know how can I modify my code for my enemy to be able to move automatically in my grid ?
This is my code below :
[using System.Collections;
using UnityEngine;
class Enemy : MonoBehaviour {
private float moveSpeed = 50f;
private float gridSize = 18f;
private enum Orientation {
Horizontal,
Vertical
};
private Orientation gridOrientation = Orientation.Vertical;
private bool allowDiagonals = false;
private bool correctDiagonalSpeed = true;
private Vector2 input;
private bool isMoving = false;
private Vector3 startPosition;
private Vector3 endPosition;
private float t;
private float factor;
public void Update() {
if (!isMoving) {
input = new Vector2(Input.GetAxis("Horizontal"), Input.GetAxis("Vertical"));
if (!allowDiagonals) {
if (Mathf.Abs(input.x) > Mathf.Abs(input.y)) {
input.y = 0;
} else {
input.x = 0;
}
}
if (input != Vector2.zero) {
StartCoroutine(move(transform));
}
}
}
public IEnumerator move (Transform transform)
{
isMoving = true;
startPosition = transform.position;
t = 0;
if (gridOrientation == Orientation.Horizontal) {
endPosition = new Vector3 (startPosition.x + System.Math.Sign (input.x) * gridSize,
startPosition.y, startPosition.z + System.Math.Sign (input.y) * gridSize);
} else {
endPosition = new Vector3 (startPosition.x + System.Math.Sign (input.x) * gridSize,
startPosition.y + System.Math.Sign (input.y) * gridSize, startPosition.z);
}
if (allowDiagonals && correctDiagonalSpeed && input.x != 0 && input.y != 0) {
factor = 0.7071f;
} else {
factor = 1f;
}
while (t < 1f) {
t += Time.deltaTime * (moveSpeed / gridSize) * factor;
transform.position = Vector3.Lerp (startPosition, endPosition, t);
yield return null;
}
isMoving = false;
yield return 0;
}
}
]

Related

Coding smoother Shooting Recoil

So, I started following a tutorial and then added some other things that I needed and everything works fine, even the recoil, but the problem is that it is really choppy, it moves once a frame and it isn't smooth at all (which is what I want) I don't know a lot about programming so I hope you can help me :)
My code:
using System.Collections;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Audio;
public class GunController : MonoBehaviour
{
[Header("Gun Setting")]
public float fireRate = 0.1f;
public int clipSize = 30;
public int reservedAmmoCapacity = 270;
//Variables that change throughout the code
bool canShoot;
int _currentAmmoInClip;
int _ammoInReserve;
//Muzzle Flash
public ParticleSystem muzzleFlash;
//Aiming
public Vector3 normalLocalPosition;
public Vector3 aimingLocalPosition;
public float aimSmoothing = 10;
[Header("Mouse Settings")]
public float mouseSensitivity = 1;
Vector2 _currentRotation;
public float weaponSwayAmount = 10;
//Weapon Recoil
public bool randomizeRecoil;
public Vector2 randomRecoilConstraints;
//You only need to assign if randomize recoil is off
public Vector2[] recoilPattern;
//Audio
AudioSource shootingSound;
//Reloading
public float reloadTime = 1.5f;
private void Start()
{
_currentAmmoInClip = clipSize;
_ammoInReserve = reservedAmmoCapacity;
canShoot = true;
shootingSound = GetComponent<AudioSource>();
}
private void Update()
{
DetermineAim();
DetermineRotation();
if (Input.GetMouseButton(0) && canShoot && _currentAmmoInClip > 0)
{
shootingSound.Play();
StartCoroutine(FinishShooting());
muzzleFlash.Play();
canShoot = false;
_currentAmmoInClip--;
StartCoroutine(ShootGun());
}
else if (Input.GetKeyDown(KeyCode.R) && _currentAmmoInClip < clipSize && _ammoInReserve > 0)
{
StartCoroutine(Reload());
}
}
void DetermineRotation()
{
Vector2 mouseAxis = new Vector2(Input.GetAxisRaw("Mouse X"), Input.GetAxisRaw("Mouse Y"));
mouseAxis *= mouseSensitivity;
_currentRotation += mouseAxis;
_currentRotation.y = Mathf.Clamp(_currentRotation.y, -90, 90);
transform.localPosition += (Vector3)mouseAxis * weaponSwayAmount / 1000;
transform.root.localRotation = Quaternion.AngleAxis(_currentRotation.x, Vector3.up);
transform.parent.localRotation = Quaternion.AngleAxis(-_currentRotation.y, Vector3.right);
}
void DetermineAim()
{
Vector3 target = normalLocalPosition;
if (Input.GetMouseButton(1)) target = aimingLocalPosition;
Vector3 desiredPosition = Vector3.Lerp(transform.localPosition, target, Time.deltaTime * aimSmoothing);
transform.localPosition = desiredPosition;
}
void DetermineRecoil()
{
transform.localPosition -= Vector3.forward * 0.1f;
if (randomizeRecoil)
{
float xRecoil = Random.Range(-randomRecoilConstraints.x, randomRecoilConstraints.x);
float yRecoil = Random.Range(-randomRecoilConstraints.y, randomRecoilConstraints.y);
Vector2 recoil = new Vector2(xRecoil, yRecoil);
_currentRotation += recoil;
}
else
{
int currentStep = clipSize + 1 - _currentAmmoInClip;
currentStep = Mathf.Clamp(currentStep, 0, recoilPattern.Length - 1);
_currentRotation += recoilPattern[currentStep];
}
}
IEnumerator ShootGun()
{
_currentAmmoInClip -= 1;
DetermineRecoil();
RayCastEnemy();
yield return new WaitForSeconds(fireRate);
canShoot = true;
}
void RayCastEnemy()
{
RaycastHit hit;
if (Physics.Raycast(transform.parent.position, transform.parent.forward, out hit, 1 << LayerMask.NameToLayer("Enemy")))
{
try
{
Debug.Log("Hit an enemy");
Rigidbody rb = hit.transform.GetComponent<Rigidbody>();
rb.constraints = RigidbodyConstraints.None;
rb.AddForce(transform.parent.transform.forward * 50);
}
catch { }
}
}
IEnumerator FinishShooting()
{
yield return new WaitForSeconds(0.3f);
shootingSound.Stop();
}
IEnumerator Reload()
{
canShoot = false;
yield return new WaitForSeconds(reloadTime);
int amountNeeded = clipSize - _currentAmmoInClip;
if (amountNeeded > _ammoInReserve)
{
_currentAmmoInClip += _ammoInReserve;
_ammoInReserve -= amountNeeded;
canShoot = true;
}
else
{
canShoot = false;
_currentAmmoInClip = clipSize;
_ammoInReserve -= amountNeeded;
canShoot = true;
}
}
}
I don't see the function DetermineRecoil() called anywhere in the code, but maybe this solution will work:
let _currentRotation = Vector2.Lerp(_currentRotation, _currentRotation + recoilPattern[currentStep], 10*Time.deltaTime);
It will change the value of _currentRotation smoothly.

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. The script below is attached to each missile.
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 section below is the code for creating the missile and is part of the enemy weapon firing script.
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

How can i check when the object MoveTowards has reached to the new position and then rotate it?

private void MoveToNewFormation()
{
squadMembers = GameObject.FindGameObjectsWithTag("Squad Member");
float step = speed * Time.deltaTime;
for (int i = 0; i < squadMembers.Length; i++)
{
squadMembers[i].transform.LookAt(newpos[i]);
squadMembers[i].transform.position = Vector3.MoveTowards(squadMembers[i].transform.position, newpos[i], step);
//squadMembers[i].transform.rotation = qua[i];
}
}
And calling it in the Update:
void Update()
{
if (Input.GetKeyDown(KeyCode.F))
{
ChangeFormation();
}
if (move == true)
MoveToNewFormation();
}
Once when one of the squadMembers reached to the newpos then i want to make
squadMembers[i].transform.rotation = qua[i];
qua is a List and i want to rotate the squad member once he reached the newpos.
Inside MoveToNewFormation i thought to add after the loop the line:
if (squadMembers[i].transform.position == newpos[i])
{
squadMembers[i].transform.rotation = qua[i];
}
But it's after the loop so 'i' not exist.
This is the complete script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SquadFormation : MonoBehaviour
{
enum Formation
{
Square, Circle, Triangle
}
public Transform squadMemeber;
public int columns = 4;
public int squareSpace = 10;
public int circleSpace = 40;
public int numberOfObjects = 20;
public float yOffset = 0;
public float speed = 3;
private Formation formation;
private GameObject[] squadMembers;
private List<Quaternion> qua = new List<Quaternion>();
private List<Vector3> newpos = new List<Vector3>();
private bool move = false;
// Use this for initialization
void Start()
{
formation = Formation.Square;
ChangeFormation();
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.F))
{
ChangeFormation();
}
if (move == true)
MoveToNewFormation();
}
private void ChangeFormation()
{
switch (formation)
{
case Formation.Square:
FormationSquare();
break;
case Formation.Circle:
FormationCircle();
break;
}
}
private Vector3 FormationSquarePositionCalculation(int index) // call this func for all your objects
{
float posX = (index % columns) * squareSpace;
float posY = (index / columns) * squareSpace;
return new Vector3(posX, posY);
}
private void FormationSquare()
{
for (int i = 0; i < numberOfObjects; i++)
{
Transform go = Instantiate(squadMemeber);
Vector3 pos = FormationSquarePositionCalculation(i);
go.position = new Vector3(transform.position.x + pos.x, 0, transform.position.y + pos.y);
go.Rotate(new Vector3(0, -90, 0));
go.tag = "Squad Member";
}
formation = Formation.Circle;
}
private Vector3 FormationCirclePositionCalculation(Vector3 center, float radius, int index, float angleIncrement)
{
float ang = index * angleIncrement;
Vector3 pos;
pos.x = center.x + radius * Mathf.Sin(ang * Mathf.Deg2Rad);
pos.z = center.z + radius * Mathf.Cos(ang * Mathf.Deg2Rad);
pos.y = center.y;
return pos;
}
private void FormationCircle()
{
Vector3 center = transform.position;
float radius = (float)circleSpace / 2;
float angleIncrement = 360 / (float)numberOfObjects;
for (int i = 0; i < numberOfObjects; i++)
{
Vector3 pos = FormationCirclePositionCalculation(center, radius, i, angleIncrement);
var rot = Quaternion.LookRotation(center - pos);
pos.y = Terrain.activeTerrain.SampleHeight(pos);
pos.y = pos.y + yOffset;
newpos.Add(pos);
qua.Add(rot);
}
move = true;
formation = Formation.Square;
}
private void MoveToNewFormation()
{
squadMembers = GameObject.FindGameObjectsWithTag("Squad Member");
float step = speed * Time.deltaTime;
for (int i = 0; i < squadMembers.Length; i++)
{
squadMembers[i].transform.LookAt(newpos[i]);
squadMembers[i].transform.position = Vector3.MoveTowards(squadMembers[i].transform.position, newpos[i], step);
//squadMembers[i].transform.rotation = qua[i];
}
//if (squadMembers[i].transform.position == newpos[i])
}
}
You can use a threshold and check the distance using that threshold.
Define threshold like this at start of script.
public float threshold = 0.1f;
Then change the MoveToNewFormation() function like this:
private void MoveToNewFormation()
{
squadMembers = GameObject.FindGameObjectsWithTag("Squad Member");
float step = speed * Time.deltaTime;
for (int i = 0; i < squadMembers.Length; i++)
{
squadMembers[i].transform.LookAt(newpos[i]);
squadMembers[i].transform.position =
Vector3.MoveTowards(squadMembers[i].transform.position, newpos[i], step);
if(Vector3.Distance(squadMembers[i].transform.position,newpos[i])<threshold){
squadMembers[i].transform.rotation = qua[i];
}
}
//if (squadMembers[i].transform.position == newpos[i])
}

c# does not contain a definition for and no extension method

my code:
using UnityEngine;
using System.Collections;
[RequireComponent(typeof(Controller2D))]
public class Player : MonoBehaviour
{
public float jumpHeight = 4;
public float timeToJumpApex = .4f;
float accelerationTimeAirborne = .2f;
float accelerationTimeGrounded = .1f;
float moveSpeed = 6;
float gravity;
float jumpVelocity;
Vector3 velocity;
float velocityXSmoothing;
Controller2D controller;
void Start()
{
controller = GetComponent<Controller2D>();
gravity = -(2 * jumpHeight) / Mathf.Pow(timeToJumpApex, 2);
jumpVelocity = Mathf.Abs(gravity) * timeToJumpApex;
print("Gravity: " + gravity + " Jump Velocity: " + jumpVelocity);
}
void Update()
{
if (controller.collisions.above || controller.collisions.below)
{
velocity.y = 0;
}
Vector2 input = new Vector2(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical"));
if (Input.GetKeyDown(KeyCode.Space) && controller.collisions.below)
{
velocity.y = jumpVelocity;
}
float targetVelocityX = input.x * moveSpeed;
velocity.x = Mathf.SmoothDamp(velocity.x, targetVelocityX, ref velocityXSmoothing, (controller.collisions.below) ? accelerationTimeGrounded : accelerationTimeAirborne);
velocity.y += gravity * Time.deltaTime;
controller.Move(velocity * Time.deltaTime);
}
}
Controller2D code:
using UnityEngine;
using System.Collections;
[RequireComponent(typeof(BoxCollider2D))]
public class Controller2D : MonoBehaviour
{
public LayerMask collisionMask;
const float skinWidth = .015f;
public int horizontalRayCount = 4;
public int verticalRayCount = 4;
float horizontalRaySpacing;
float verticalRaySpacing;
new BoxCollider2D collider;
RaycastOrigins raycastOrigins;
internal object collisions;
void Start()
{
collider = GetComponent<BoxCollider2D>();
CalculateRaySpacing();
}
public void Move(Vector3 velocity)
{
UpdateRaycastOrigins();
if (velocity.x != 0)
{
HorizontalCollisions(ref velocity);
}
if (velocity.y != 0)
{
VerticalCollisions(ref velocity);
}
transform.Translate(velocity);
}
void HorizontalCollisions(ref Vector3 velocity)
{
float directionX = Mathf.Sign(velocity.x);
float rayLength = Mathf.Abs(velocity.x) + skinWidth;
for (int i = 0; i < horizontalRayCount; i++)
{
Vector2 rayOrigin = (directionX == -1) ? raycastOrigins.bottomLeft : raycastOrigins.bottomRight;
rayOrigin += Vector2.up * (horizontalRaySpacing * i);
RaycastHit2D hit = Physics2D.Raycast(rayOrigin, Vector2.right * directionX, rayLength, collisionMask);
Debug.DrawRay(rayOrigin, Vector2.right * directionX * rayLength, Color.red);
if (hit)
{
velocity.x = (hit.distance - skinWidth) * directionX;
rayLength = hit.distance;
}
}
}
void VerticalCollisions(ref Vector3 velocity)
{
float directionY = Mathf.Sign(velocity.y);
float rayLength = Mathf.Abs(velocity.y) + skinWidth;
for (int i = 0; i < verticalRayCount; i++)
{
Vector2 rayOrigin = (directionY == -1) ? raycastOrigins.bottomLeft : raycastOrigins.topLeft;
rayOrigin += Vector2.right * (verticalRaySpacing * i + velocity.x);
RaycastHit2D hit = Physics2D.Raycast(rayOrigin, Vector2.up * directionY, rayLength, collisionMask);
Debug.DrawRay(rayOrigin, Vector2.up * directionY * rayLength, Color.red);
if (hit)
{
velocity.y = (hit.distance - skinWidth) * directionY;
rayLength = hit.distance;
}
}
}
void UpdateRaycastOrigins()
{
Bounds bounds = collider.bounds;
bounds.Expand(skinWidth * -2);
raycastOrigins.bottomLeft = new Vector2(bounds.min.x, bounds.min.y);
raycastOrigins.bottomRight = new Vector2(bounds.max.x, bounds.min.y);
raycastOrigins.topLeft = new Vector2(bounds.min.x, bounds.max.y);
raycastOrigins.topRight = new Vector2(bounds.max.x, bounds.max.y);
}
void CalculateRaySpacing()
{
Bounds bounds = collider.bounds;
bounds.Expand(skinWidth * -2);
horizontalRayCount = Mathf.Clamp(horizontalRayCount, 2, int.MaxValue);
verticalRayCount = Mathf.Clamp(verticalRayCount, 2, int.MaxValue);
horizontalRaySpacing = bounds.size.y / (horizontalRayCount - 1);
verticalRaySpacing = bounds.size.x / (verticalRayCount - 1);
}
struct RaycastOrigins
{
public Vector2 topLeft, topRight;
public Vector2 bottomLeft, bottomRight;
}
}
When I hover over "above" and "below" it give me the error
c# does not contain a definition for and no extension method,
can anyone see what I have done wrong?
internal object collisions;
Here you define collisions as object. Which means it does not have above nor below boolean properties.
Perhaps you need to define a new struct or class called collisions and define internal or public boolean properties above and below.

Change Gizmos.DrawWireCube Cube Limits, based in childs transform.position

How can change width of Gizmos.DrawWireCube, based in child transforms (Gizmos.DrawWireSphere) transform.position or maybe the left/right limit of the transform?
My code so far:
position.cs
using UnityEngine;
using System.Collections;
public class Position : MonoBehaviour {
void OnDrawGizmos () {
Gizmos.DrawWireSphere(transform.position, 0.75f);
}
}
FormationController.cs
using UnityEngine;
using System.Collections;
public class FormationController : MonoBehaviour {
public GameObject enemyPrefab;
public float width = 10;
public float height = 5;
public float speed = 5;
public float padding = 1.5f;
public float SpawnDelaySeconds = 1;
private int direction = 1;
private float boundaryLeftEdge,boundaryRightEdge;
private PlayerController playerController;
// Use this for initialization
void Start () {
float distance = transform.position.z - Camera.main.transform.position.z;
Vector3 leftmost = Camera.main.ViewportToWorldPoint(new Vector3(0, 0, distance));
Vector3 rightmost = Camera.main.ViewportToWorldPoint(new Vector3(1, 0, distance));
boundaryLeftEdge = leftmost.x + padding;
boundaryRightEdge = rightmost.x - padding;
SpawnUntilFull();
}
void OnDrawGizmos () {
Gizmos.DrawWireCube(transform.position, new Vector3 (width, height));
}
// Update is called once per frame
void Update () {
float formationRightEdge = transform.position.x + 0.5f * width;
float formationLeftEdge = transform.position.x - 0.5f * width;
if (formationRightEdge > boundaryRightEdge) {
direction = -1;
}
if (formationLeftEdge < boundaryLeftEdge) {
direction = 1;
}
transform.position += new Vector3(direction * speed * Time.deltaTime, 0, 0);
if (AllEnemiesAreDead()) {
SpawnUntilFull();
}
}
void SpawnUntilFull () {
Transform freePos = NextFreePosition();
GameObject enemy = Instantiate(enemyPrefab, freePos.position, Quaternion.identity) as GameObject;
enemy.transform.parent = freePos;
if (FreePositionExists()) {
Invoke ("SpawnUntilFull", SpawnDelaySeconds);
}
}
bool FreePositionExists () {
foreach( Transform position in transform) {
if (position.childCount <= 0) {
return true;
}
}
return false;
}
Transform NextFreePosition() {
foreach (Transform position in transform) {
if (position.childCount <= 0) {
return position;
}
}
return null;
}
bool AllEnemiesAreDead () {
foreach(Transform position in transform) {
if (position.childCount > 0) {
return false;
}
}
return true;
}
}
An example:
I'm making a game like "space invaders", but i can't figured out how when the most left invader die, the invaders formation changes to smaller formation... so the new most left invader "touches" the left boundary.
My scene:
Ignore the gizmo (the circle) at the most top
try this:
using UnityEngine;
using System.Collections;
public class FormationController : MonoBehaviour {
public GameObject enemyPrefab;
public float widthToLeft = 5;
public float widthToRight = 5;
public float height = 5;
public float speed = 5;
public float padding = 1.5f;
public float SpawnDelaySeconds = 1;
private int direction = 1;
private float boundaryLeftEdge,boundaryRightEdge;
private PlayerController playerController;
// Use this for initialization
void Start () {
float distance = transform.position.z - Camera.main.transform.position.z;
Vector3 leftmost = Camera.main.ViewportToWorldPoint(new Vector3(0, 0, distance));
Vector3 rightmost = Camera.main.ViewportToWorldPoint(new Vector3(1, 0, distance));
boundaryLeftEdge = leftmost.x + padding;
boundaryRightEdge = rightmost.x - padding;
SpawnUntilFull();
}
void OnDrawGizmos () {
Gizmos.DrawWireCube(transform.position, new Vector3 (widthToLeft+widthToRight, height));
}
// Update is called once per frame
void Update () {
float formationRightEdge = transform.position.x + 0.5f * widthToRight;
float formationLeftEdge = transform.position.x - 0.5f * widthToLeft;
if (formationRightEdge > boundaryRightEdge) {
direction = -1;
}
if (formationLeftEdge < boundaryLeftEdge) {
direction = 1;
}
transform.position += new Vector3(direction * speed * Time.deltaTime, 0, 0);
if (AllEnemiesAreDead()) {
SpawnUntilFull();
}
}
void SpawnUntilFull () {
Transform freePos = NextFreePosition();
GameObject enemy = Instantiate(enemyPrefab, freePos.position, Quaternion.identity) as GameObject;
enemy.transform.parent = freePos;
if (FreePositionExists()) {
Invoke ("SpawnUntilFull", SpawnDelaySeconds);
}
}
bool FreePositionExists () {
foreach( Transform position in transform) {
if (position.childCount <= 0) {
return true;
}
}
return false;
}
Transform NextFreePosition() {
foreach (Transform position in transform) {
if (position.childCount <= 0) {
return position;
}
}
return null;
}
bool AllEnemiesAreDead () {
foreach(Transform position in transform) {
if (position.childCount > 0) {
return false;
}
}
return true;
}
}
i just changed width to widthToLeft and widthToRight
when the invader dies:
public void OnInvaderDeath() {
float mostLeft = 10000;
float mostRight = -10000;
foreach( Transform invaderTransform in invaderList ) {
if( invaderTransform.position.x < mostLeft )
mostLeft = invaderTransform.position.x;
if( invaderTransform.position.x > mostRight )
mostRight = invaderTransform.position.x;
}
widthToLeft = mostLeft + 0.75f;
widthToRight = mostRight + 0.75f;
}

Categories

Resources