Unity: Overlapping spawn Random Objects at Random Positions in C# - c#

I am trying to develop a 2d game where my enemies will pop-up and disappear in random position without overlapping with each other. I am following this tutorial in youtube https://www.youtube.com/watch?v=iLTP4EbM1N4 but when my player touch a enemy then he is losing 2 lives instead of 1. I think it's because enemies randomly spawn in the same spawnpoint (I have 5 enemies). Do you have any suggestion how to fix that? Any help would be highly appreciated. Thanks in advance. Here is my two scripts:
SpawnItems.cs
using UnityEngine;
using System.Collections;
public class SpawnItems : MonoBehaviour
{
public Transform[] SpawnPoints;
public float spawnTime = .5f;
public GameObject[] Coins;
void Start ()
{
InvokeRepeating ("SpawnCoins", spawnTime, spawnTime);
}
void Update ()
{
}
void SpawnCoins()
{
for (int i = 0; i < Coins.Length; i++) {
int spawnIndex = Random.Range (0, SpawnPoints.Length);
//int objectIndex = Random.Range (0, Coins.Length);
Instantiate (Coins [i], SpawnPoints [spawnIndex].position, SpawnPoints [spawnIndex].rotation);
}
}
Destroy.cs
using UnityEngine;
using System.Collections;
public class DestoryScript: MonoBehaviour
{
public float destoryTime = .5f;
private float rotateSpeed = 300.0f;
void Start ()
{
Destroy (gameObject, destoryTime);
}
void Update ()
{
transform.Rotate (Vector3.forward * Time.deltaTime * rotateSpeed);
}
}
Orange ball overlaps with green ball

Your SpawnCoins() in SpawnItems.cs should be like:
void SpawnCoins()
{
Transform currentSpawnPoint = SpawnPoints[Random.Range(0, SpawnPoints.Length)].transform;
Instantiate (Coins [Random.Range(0, Coins.Length)], currentSpawnPoint.position, currentSpawnPoint.rotation);
}

Related

How can I make a bullet loop around once and continue in the direction it was heading?

relatively new to C#/Unity and was having some trouble coming up with how to implement a certain bullet behavior.
What I'm trying to do is have the bullet move in a specific direction for some amount of time and then loop back around in a circle, and then continue on in the direction it was heading.
Like this:
diagram
Here's the code I'm working with, it's a basic script that moves the bullet and then despawns it with a coroutine after a while.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Lean.Pool;
public class CynthiaSubShotBehavior : MonoBehaviour
{
GameObject CurrentChar;
PlayerInput playerInput;
Vector3 _cameraPos;
Vector2 shotVelocity;
float shotSmoothingX;
float shotSmoothingY;
public float shotSmoothingTime;
public float shotSpeed;
public float focusedShotSpeed;
public float disableTime;
void Awake(){
CurrentChar = GameObject.FindWithTag("Cynthia [12]");
playerInput = CurrentChar.GetComponent<PlayerInput>();
_cameraPos = Camera.main.WorldToViewportPoint(transform.position);
}
void OnEnable(){
shotVelocity.x = (playerInput.isFocused)? focusedShotSpeed:shotSpeed;
StartCoroutine(Disable());
}
void Update(){
CalculateShotVelocity();
}
void FixedUpdate(){
transform.Translate(shotVelocity * Time.deltaTime);
}
void CalculateShotVelocity(){
shotVelocity.x = Mathf.SmoothDamp(shotVelocity.x, 0f, ref shotSmoothingX, shotSmoothingTime);
shotVelocity.y = Mathf.SmoothDamp(shotVelocity.y, 0f, ref shotSmoothingY, shotSmoothingTime);
}
IEnumerator Disable(){
yield return new WaitForSeconds(disableTime);
LeanPool.Despawn(this);
}
}
Any ideas?

I can not play animation on AI, unity 2d

I tried to make a firefly for my game, which is an AI.I wanted it to make across the map, for that I watched a tutorial on YT from BlackThornProd, but when I tried animating it, and played the game, it was terrible, the animation were playing bizarre, like when the firefly needs to go on the right, the animations are playing like this; Left-Right-Idle-Right-etc.Im using Blend Tree.
How can I solve it?
Thanks
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class NPCRandomMoveing : MonoBehaviour
{
public float speed;
public Transform[] moveSpots;
private int randomSpot;
private float waitTime;
public float startWaitTime;
public Animator anim;
Vector2 movement;
void Start()
{
waitTime = startWaitTime;
randomSpot = Random.Range(0, moveSpots.Length);
}
void Update()
{
transform.position = Vector2.MoveTowards(transform.position, moveSpots[randomSpot].position, speed * Time.deltaTime);
if(Vector2.Distance(transform.position, moveSpots[randomSpot].position) < 0.2f){
if(waitTime <= 0){
randomSpot = Random.Range(0, moveSpots.Length);
waitTime = startWaitTime;
} else {
waitTime -= Time.deltaTime;
}
}
}
void FixedUpdate(){
anim.SetFloat("Horizontal", transform.position.x);
anim.SetFloat("Vertical", transform.position.y);
anim.SetFloat("Speed", transform.position.sqrMagnitude);
}
}
I think you move your fly and also try to animate its position right? Try maybe to just animate and dont change the transforms or even better rotate your fly with lookat vector and use animation controler to just adjust the speed of wings.
Try this script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class RotateTowardsSpline : MonoBehaviour
{
// put the points from unity interface
public List<Transform> wayPointList = new List<Transform>();
public int currentWayPoint = 0;
Transform targetWayPoint;
public float speed = 0f;
public float turningRate = 1f;
// Use this for initialization
void Start()
{
}
// Update is called once per frame
void FixedUpdate()
{
if (currentWayPoint < this.wayPointList.Count - 1)
{
if (targetWayPoint == null)
targetWayPoint = wayPointList[currentWayPoint];// hier put a random nr
RotateTowards();
}
}
void RotateTowards()
{
// rotate towards the target
transform.forward = Vector3.RotateTowards(transform.right, targetWayPoint.position - transform.position, 0.02f * (speed) * Time.deltaTime, 1.0f);
}
}

Infinite runner has bumps. How do I smooth it?

I have a script that spawns my ground prefabs infinitely. The only problem is that occasionally there is a "bump" for the player to hit at the boundary of a new ground prefab.
It seems like one prefab is slightly higher than the previous one and when the player hits that small bump they go flying. How do I fix this?
I might just make the player a game object instead of a rigidbody and animate it instead of using actual physics.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GroundManager : MonoBehaviour
{
//oH is object height
public GameObject[] ground;
public GameObject[] obstacles;
private Transform playerTransform;
private float spawnZ = 0.0f;
private float spawnO = 0.0f;
public float oH;
private float tileLength = 40.0f;
private float oLength = 36.0f;
private int tilesOnScreen = 8;
void Start()
{
playerTransform = GameObject.FindGameObjectWithTag("Player").transform;
for (int i = 0; i < tilesOnScreen; i++)
{
SpawnTile();
SpawnObstacle();
}
}
// Player must be tagged "Player"
void Update()
{
if (playerTransform.position.z > (spawnZ - tilesOnScreen * tileLength))
{
SpawnTile();
SpawnObstacle();
}
}
private void SpawnTile(int prefabIndex = -1)
{
GameObject go;
go = Instantiate(ground[0]) as GameObject;
go.transform.SetParent(transform);
go.transform.position = Vector3.forward * spawnZ;
spawnZ += tileLength;
}
private void SpawnObstacle()
{
GameObject go;
go = Instantiate(obstacles[Random.Range(0, obstacles.Length)]) as GameObject;
go.transform.SetParent(transform);
go.transform.position = new Vector3(0, oH, 1 * spawnO);
spawnO += oLength;
}
}
This code works to infinitely spawn the ground objects but has the bumps that I described. Just one bump is enough to screw up the whole game.

Why is my enemy script not following the Player?

Why is my enemy script not following the Player ?
using UnityEngine;
using System.Collections;
public class suivre : MonoBehaviour {
GameObject perso;
float persoposx;
float persoposy;
float persoposz;
// Use this for initialization
void Start () {
perso = GameObject.FindGameObjectWithTag ("Player");
InvokeRepeating ("follower", 1, 1);
}
// Update is called once per frame
void Update () {
persoposx = perso.transform.position.x;
persoposy = perso.transform.position.y;
persoposz = perso.transform.position.z;
}
void follower() {
GetComponent<Rigidbody>().AddForce(new Vector3(persoposx, persoposy, persoposz));
}
}
This script is a component on the enemy. The enemy doesn't follow the player, but still goes towards a direction - why?
You are missing one concept of direction vector.
Your code should look like that:
using UnityEngine;
using System.Collections;
public class suivre : MonoBehaviour
{
public float speed = 3f;
GameObject perso;
void Start ()
{
perso = GameObject.FindGameObjectWithTag ("Player");
InvokeRepeating ("follower", 1, 1);
}
void follower()
{
Vector3 directionToPlayer = perso.transform.position - this.transform.position;
directionToPlayer.Normalize ();
GetComponent<Rigidbody>().AddForce(directionToPlayer * speed);
}
}
Get rid of Update method. You don't need it here.
Then create direction vector from enemy to player, normalize it, and then pass this vector to AddForce and multiply it by speed you want.

How to spawn enemy at random intervals?

I am using EnemyScript to move the enemy towards the player and killing the player, but I'm unable to spawn it randomly in code. I am currently spawning it directly through screen by placing the prefab on the scene.
Here is my EnemyScript
using UnityEngine;
using System.Collections;
public class EnemyScript : MonoBehaviour {
public Transform target;
public float speed = 2f;
void Update ()
{
transform.position = Vector2.MoveTowards(transform.position, target.position, speed * Time.deltaTime);
}
void OnTriggerEnter2D(Collider2D otherCollider)
{
PlayerControl shot = otherCollider.gameObject.GetComponent<PlayerControl>();
if (shot != null)
{
Destroy(shot.gameObject);
}
}
}
you could use something similar to this:
public GameObject myObj;
void Start ()
{
enemy = GameObject.Find("enemy");
InvokeRepeating("SpawnEnemy", 1.6F, 1F);
}
public void SpawnEnemy()
{
Vector3 position = new Vector3(Random.Range(35.0F, 40.0F), Random.Range(-4F, 2F), 0);
Instantiate(myObj, position, Quaternion.identity);
}
in the InvokeRepeating call you could possibly add the random range there also instead of a timed instantiate. This example is just a snippet of some prototype code i did a while ago, it may not suit your needs directly but hopefully will give you a general idea on what to do.
EDIT: to make sense, put this into a blank object somewhere in your scene, dont attach this to the actual enemy.
i programmed it like this.
public GameObject enemyPrefab;
public float numEnemies;
public float xMin = 20F;
public float xMax = 85F;
public float yMin = 3.5F;
public float yMax = -4.5F;
void Start () {
for (int i=0; i< numEnemies; i++) {
Vector3 newPos = new Vector3(Random.Range(xMin,xMax),Random.Range(yMin,yMax),0);
GameObject enemy = Instantiate(enemyPrefab,newPos,Quaternion.identity) as GameObject;
}
}
This will spawn a random number of enemies, at random locations, after random periods of time, all adjustable in the Inspector.
public float minTime = 1;
public float maxTime = 3;
public int minSpawn = 1;
public int maxSpawn = 4;
public Bounds spawnArea; //set these bounds in the inspector
public GameObject enemyPrefab;
private spawnTimer = 0;
Vector3 randomWithinBounds(Bounds r) {
return new Vector3(
Random.Range(r.min.x, r.max.x),
Random.Range(r.min.y, r.max.y),
Random.Range(r.min.z, r.max.z));
}
void Update() {
spawnTimer -= Time.deltaTime;
if(spawnTimer <= 0) {
spawnTimer += Random.Range(minTime, maxTime);
int randomSpawnCount = Random.Range(minSpawn, maxSpawn);
for(int i = 0; i < randomSpawnCount; i++) {
Instantiate(transform.transformPoint(enemyPrefab), randomWithinBounds(spawnArea), Quaternion.identity);
}
}
}
//bonus: this will show you the spawn area in the editor
void OnDrawGizmos() {
Gizmos.matrix = transform.localToWorldMatrix;
Gizmos.color = Color.yellow;
Gizmos.drawWireCube(spawnArea.center, spawnArea.size);
}
People on here seem to like using coroutines for time delays, but I personally prefer to track my own timers in Update() to maximize control and predictability.

Categories

Resources