Setting the spawn position for a 3D object - c#

I am making an endless runner style game in unity where the floor tiles spawn randomly and endlessly in front of the player as they run and delete themselves after a certain distance behind the player this is all working fine and as intended however the individual tiles spawn about half way inside each other and as much as I try to debug my code I can't seem to effect them. Ideally, I want the code to do exactly what it's doing, but the tiles spawn end to end rather than inside each other.
Any help would be greatly appreciated.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Tile_Manager : MonoBehaviour
{
public GameObject[] tilePrefabs;
private Transform playerTransform;
private float spawnZ = 5.0f;
private float tileLength = 5.0f;
private float safeZone = 7.0f;
private int amtTilesOnScreen = 10;
private int lastPrefabIndex = 0;
private List<GameObject> activeTiles;
// Use this for initialization
void Start () {
activeTiles = new List<GameObject>();
playerTransform = GameObject.FindGameObjectWithTag ("Player").transform;
for (int i = 0; i < amtTilesOnScreen; i++)
{
if (i < 2)
SpawnTile(0);
else
SpawnTile();
}
}
// Update is called once per frame
void Update () {
if (playerTransform.position.z - safeZone > (spawnZ - amtTilesOnScreen * tileLength))
{
SpawnTile();
DeleteTile();
}
}
private void SpawnTile(int prefabIndex = -1)
{
GameObject go;
if (prefabIndex == -1)
go = Instantiate(tilePrefabs[RandomPrefabIndex()]) as GameObject;
else
go = Instantiate(tilePrefabs[prefabIndex]) as GameObject;
go.transform.SetParent(transform);
go.transform.position = Vector3.forward * spawnZ;
spawnZ += tileLength;
activeTiles.Add (go);
}
private void DeleteTile()
{
Destroy(activeTiles [0]);
activeTiles.RemoveAt (0);
}
private int RandomPrefabIndex()
{
if (tilePrefabs.Length <= 1)
return 0;
int randomIndex = lastPrefabIndex;
while (randomIndex == lastPrefabIndex)
{
randomIndex = Random.Range(0, tilePrefabs.Length);
}
lastPrefabIndex = randomIndex;
return randomIndex;
}
}
stacked tiles

You need to take the length of a tile into account. Try changing this
go.transform.position = Vector3.forward * spawnZ;
to this
go.transform.position = Vector3.forward * (spawnZ + tileLength / 2);
to add half the tile length to the spawn position.

Wouldn't you want
go.transform.Translate(Vector3.forward * spawnZ);
not position?
As you're spawning things relative to the world coordinate system.
https://docs.unity3d.com/ScriptReference/Transform.Translate.html

Related

Creating a color loop effect in Unity?

I'm currently developing a game in Unity and I ran into a small problem. I'm trying to generate a rainbow color effect that is similar to what happens when someone catches a star in mario kart or supermario on a specific gameobject. Essentially all the instances of the prefab attached to the script InteractControl that are active should get this effect (Either loop or lerp trough 5 different colors continusesly) while the variable timeLeft > 0 and the score > 10 and then go back to the original value of the color they had when timeLeft < 0.
Ive already tried multiple things including using a coroutine, and reseting the color inisde of it multiple times. Creating a new method and allowing acces to it only if a bool whom's value is set within the timeleft > 0 if statement is true, or currently trying to lerp the color however this all doesnt seem the work. Trying to make an animation could also be an option however its too complicated to make the objects of different colours match the same dimensions as the original I have so I really want to make it change trough the script.
These are the relevant parts of the script in question:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class InteractControl : MonoBehaviour, IPooledObject
{
public Transform[] spawnPoints;
public Color[] _colors;
private float t = 0.2f;
private Rigidbody2D rb;
GameObject target;
Vector3 directionToTarget;
public static int LevelStart = 0;
public static float moveSpeed = 5f;
public static bool isSlowMotion = true;
public static float timeLeft = 12f;
private float randomSpawnTime;
private int Spawn = 1;
private float scaledTime;
private Color oldColor;
private Color newColor;
private float newT;
private void Start()
{
scaledTime = Mathf.Sin(t) * (float)(5 - 1);
oldColor = _colors[(int)scaledTime];
newColor = _colors[(int)(scaledTime + 1f)];
newT = scaledTime - Mathf.Round(scaledTime);
}
public void OnObjectSpawn()
{
target = GameObject.FindWithTag("White Ball");
rb = GetComponent<Rigidbody2D>();
}
void Update()
{
if (target != null)
{
if (ScoreScript.scoreValue > 10)
{
timeLeft -= Time.deltaTime;
if (timeLeft > 0)
{
directionToTarget = (target.transform.position - transform.position).normalized;
rb.velocity = new Vector2(directionToTarget.x * moveSpeed,
directionToTarget.y * moveSpeed);
GetComponent<Renderer>().material.color = Color.Lerp(oldColor, newColor, 5f);
if (Spawn == 1)
{
randomSpawnTime = Random.Range(2, 8);
Spawn++;
}
if (timeLeft < randomSpawnTime && Spawn <= 2)
{
BallSpawnerControl.ClockSpawn = true;
}
}
if (timeLeft < 0)
{
GameObject[] gos = GameObject.FindGameObjectsWithTag("ColouredBall Highress");
foreach (GameObject go in gos)
{
go.SetActive(false);
}
BallSpawnerControl.HeartSpawn = true;
}
}
}
}
}

Moving a ball to Random Coordinates in Unity

The story is that I have this research project in which I have to simulate a tracking experiment.
I have a ball in a box (which we hope can be implemented as a VR room in the future), and the ball moves to random coordinates.
I also plan on adding another object that the user can click on (or in the case of VR, use a joystick) to move and follow the ball.
The coordinates of each movement of the ball, and the coordinates of each movement of the object must be outputted to a file.
Right now, I am having difficulty sending the ball to random coordinates.
The ball is named "Player" and the file is named "PlayerController." The two issues are that while utilizing the Unity version of Random, I consistently attain the same coordinates on each run and the ball does not stop moving.
My code is attached below. Also, if any of you readers have an idea on how to implement the rest of my project, suggestions are definitely appreciated!
Thank you so much!
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
public class PlayerController : MonoBehaviour {
private float movementDuration = 2.0f;
private float waitBeforeMoving = 2.0f;
private bool hasArrived = false;
private Coroutine moveCoroutine = null;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if (!hasArrived)
{
hasArrived = true;
Vector3[] v = new Vector3[20];
for (int i=0; i<v.Length; i++)
{
Random.InitState(System.DateTime.Now.Millisecond);
v[i] = new Vector3(Random.Range(-10.0f, 10.0f),
Random.Range(-10.0f, 10.0f),
Random.Range(-10.0f, 10.0f));
moveCoroutine = StartCoroutine(MoveToPoint(v[i]));
}
}
if (Input.GetMouseButtonDown(0))
StopMovement();
}
private IEnumerator MoveToPoint(Vector3 targetPos)
{
float timer = 0.0f;
Vector3 startPos = transform.position;
while (timer < movementDuration)
{
timer += Time.deltaTime;
float t = timer / movementDuration;
t = t * t * t * (t * (6f * t - 15f) + 10f);
transform.position = Vector3.Lerp(startPos, targetPos, t);
yield return null;
}
yield return new WaitForSeconds(waitBeforeMoving);
hasArrived = false;
}
private void StopMovement()
{
if (moveCoroutine != null)
StopCoroutine(moveCoroutine);
}
public void OnCollisionEnter(Collision collision)
{
if (collision.gameObject.CompareTag("sphereTag"))
StopMovement();
}
The ball doesn't stop moving because you set hasArrived to false at the end of your coroutine so it just fires again every 2 seconds.
The coordinates were different for me every time - not sure what issue you are facing there. May be something with Random.InitState()
The way you have your loop set up, every vector in the array is getting fed into its own coroutine, but this is all happening essentially instantaneously since there is no delay before going into the next iteration of your for-loop. If you are attempting to loop through all 20 of the points you should instead call a single coroutine, with the for-loop and embedded delay inside:
bool hasArrived;
private float movementDuration = 2.0f;
private float waitBeforeMoving = 2.0f;
void Update()
{
if (!hasArrived)
{
hasArrived = true;
StartCoroutine(MoveToPoints());
}
}
private IEnumerator MoveToPoints()
{
Vector3[] v = new Vector3[20];
for (int i = 0; i < v.Length; i++)
{
float timer = 0.0f;
Vector3 startPos = transform.position;
v[i] = new Vector3(Random.Range(-10.0f, 10.0f),
Random.Range(-10.0f, 10.0f),
Random.Range(-10.0f, 10.0f));
while (timer < movementDuration)
{
timer += Time.deltaTime;
float t = timer / movementDuration;
t = t * t * t * (t * (6f * t - 15f) + 10f);
transform.position = Vector3.Lerp(startPos, v[i], t);
yield return null;
}
yield return new WaitForSeconds(waitBeforeMoving);
}
}

unity2d: randomly change position of gameobject after it has been looped

So, I am making this little game, where the character constantly moves upwards with an autoscroll camera. The character jumps from platform to platform and as soon as a platform or a background tile is nolonger visible, i loop it back up. I assigned a range to my plattforms in which a randomizer choses a value from so that the player gets an individual set of plattforms every time he or she starts the game. the problem is the looping: since i do the randomizing in the start() functions, the random poision of the plattforms is only assigned once and then looped and looped again and again. so the game gets kinda boring after a few loops with is like after 20 seconds :D
Here is my code:
private float randomFloat = 0;
private int subOrAdd = 0;
// Use this for initialization
void Start () {
subOrAdd = Random.Range(1, 10);
randomFloat = Random.Range(0f, 1.4f);
// randomly add or subtract height of object
if (subOrAdd < 6)
{
this.transform.position = new Vector2(transform.position.x, transform.position.y - randomFloat);
}
else if (subOrAdd >= 6)
{
this.transform.position = new Vector2(transform.position.x, transform.position.y + randomFloat);
}
}
Basically, I am having a hardcoded range and then randomly decide to either add or subtract the number that came out of the range. so how would i make it so, that the objects that get looped always ask for a new position? Because start is only called once as you know and even after looping, the position remains the same. I hope I made myself clear here :)
Any help would be awesome!
Here is the the code that loops the platforms:
public class PlattformLooper : MonoBehaviour {
public float spacingBetweenLoops = 0f;
private void OnTriggerEnter2D(Collider2D collider)
{
if (collider.gameObject.tag == "Plattform")
{
Debug.Log("TRIGGERED Plattform!");
float heightOfBGObj = ((BoxCollider2D)collider).size.y;
Vector3 pos = collider.transform.position;
pos.y += heightOfBGObj * (5*5)+spacingBetweenLoops;
collider.transform.position = pos;
}
}
Just extract your randomization logic into a separate method.
void Start () {
RandomizeHeight()
}
public void RandomizeHeight() {
subOrAdd = Random.Range(1, 10);
randomFloat = Random.Range(0f, 1.4f);
// randomly add or subtract height of object
if (subOrAdd < 6)
{
this.transform.position = new Vector2(transform.position.x, transform.position.y - randomFloat);
}
else if (subOrAdd >= 6)
{
this.transform.position = new Vector2(transform.position.x, transform.position.y + randomFloat);
}
}
Then you can call it whenever you want:
public class PlattformLooper : MonoBehaviour {
public float spacingBetweenLoops = 0f;
private void OnTriggerEnter2D(Collider2D collider)
{
if (collider.gameObject.tag == "Plattform")
{
Debug.Log("TRIGGERED Plattform!");
float heightOfBGObj = ((BoxCollider2D)collider).size.y;
Vector3 pos = collider.transform.position;
pos.y += heightOfBGObj * (5*5)+spacingBetweenLoops;
collider.transform.position = pos;
collider.GetComponent<YourComponent>().RandomizeHeight();
}
}

How can i make the enemy to move to next waypoint if there ius a very big waypoint in the middle?

If the waypoints are small size for example cubes at size 0.1 or 1 it's fine.
When i change the cubes size to 20-30 if there is a situation that there are two waypoints on the way but the enemy should get to the second waypoint he will stuck on the wall of the first waypoint will shake/stutter and will try to go to one of the sides and then in the end he will pass this waypoint and continue to the waypoint he should get the target.
It happen only when the waypoints(cubes) are very big and if a waypoint block the waypoint the enemy should get.
using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
using UnityStandardAssets.Characters.ThirdPerson;
public class WayPoints : MonoBehaviour {
public GameObject[] waypoints;
public Transform target;
public float moveSpeed = 10f;
public float moveSpeed1 = 10f;
public float slowDownSpeed = 3f;
public float reverseSlowDownSpeed = 3f;
public float rotationSpeed = 1f;
private Transform myTransform;
private int targetsIndex = 0;
private Vector3 originalPosition;
private GameObject[] robots;
public Transform reverseTarget;
private int reverseTargetsIndex = 0;
private Vector3 reverseOriginalPosition;
public bool random = false;
void Awake()
{
myTransform = transform;
}
// Use this for initialization
void Start()
{
waypoints = GameObject.FindGameObjectsWithTag("ClonedObject");
robots = GameObject.FindGameObjectsWithTag("Robots");
AddColliderToWaypoints();
originalPosition = robots[0].transform.position;
reverseOriginalPosition = robots[1].transform.position;
}
// Update is called once per frame
void Update()
{
if (MyCommands.walkbetweenwaypoints == true)
{
WayPointsAI();
ReverseWayPointsAI();
}
DrawLinesInScene();
}
private void WayPointsAI()
{
if (targetsIndex == waypoints.Length)
targetsIndex = 0;
target = waypoints[targetsIndex].transform;
float distance = Vector3.Distance(robots[0].transform.position, target.transform.position);
robots[0].transform.rotation = Quaternion.Slerp(robots[0].transform.rotation, Quaternion.LookRotation(target.position - robots[0].transform.position), rotationSpeed * Time.deltaTime);
//move towards the player
if (distance < 30)
{
robots[0].transform.position += robots[0].transform.forward * slowDownSpeed * Time.deltaTime;
}
else
{
robots[0].transform.position += robots[0].transform.forward * moveSpeed * Time.deltaTime;
}
if (distance < target.transform.localScale.magnitude)
{
targetsIndex++;
}
}
private void ReverseWayPointsAI()
{
if (reverseTargetsIndex == 0)
reverseTargetsIndex = waypoints.Length -1;
reverseTarget = waypoints[reverseTargetsIndex].transform;
float distance = Vector3.Distance(robots[1].transform.position, reverseTarget.transform.position);
robots[1].transform.rotation = Quaternion.Slerp(robots[1].transform.rotation, Quaternion.LookRotation(reverseTarget.position - robots[1].transform.position), rotationSpeed * Time.deltaTime);
//move towards the player
if (distance < 30)
{
robots[1].transform.position += robots[1].transform.forward * reverseSlowDownSpeed * Time.deltaTime;
}
else
{
robots[1].transform.position += robots[1].transform.forward * moveSpeed1 * Time.deltaTime;
}
if (distance < reverseTarget.transform.localScale.magnitude)
{
reverseTargetsIndex--;
}
}
void RandomWayPointsAI()
{
if (random == true)
{
int index = Random.Range(0, waypoints.Length);
target = waypoints[index].transform;
}
}
void DrawLinesInScene()
{
// draw lines between each checkpoint //
for (int i = 0; i < waypoints.Length - 1; i++)
{
Debug.DrawLine(waypoints[i].transform.position, waypoints[i + 1].transform.position, Color.blue);
}
// draw a line between the original transform start position
// and the current transform position //
Debug.DrawLine(originalPosition, robots[0].transform.position, Color.red);
Debug.DrawLine(reverseOriginalPosition, robots[1].transform.position, Color.red);
// draw a line between current transform position and the next waypoint target
// each time reached a waypoint.
if (target != null)
Debug.DrawLine(target.transform.position, robots[0].transform.position, Color.green);
if (reverseTarget != null)
Debug.DrawLine(reverseTarget.transform.position, robots[1].transform.position, Color.green);
}
void AddColliderToWaypoints()
{
foreach (GameObject go in waypoints)
{
SphereCollider sc = go.AddComponent<SphereCollider>() as SphereCollider;
sc.isTrigger = true;
}
}
}
I tried to make
if (distance < reverseTarget.transform.localScale.magnitude)
I tried before it to make
if (distance < reverseTarget.tranform.localscale.x)
Or
if (distance < reverseTarget.tranform.localscale.x / 2)
Same with target and the first AI function.
But nothing is working. Maybe i should find the waypoints radius ?
Not sure how to solve it.
What OP seems to have wanted was a way to give the AI pathfinding so that when the AI wanted to go from (dynamic/code generated) point A to B and there was an obstacle between, the AI wouldn't get stuck in the obstacle.
Unity offers NavMesh and NavMesh Obstacle, a simple pathfinding tool Unity gives us to achieve a smart AI with little effort.

objects using their own unique waypoints array

update...
First Class
using UnityEngine;
using System.Collections;
[System.Serializable]
public class Wave
{
public GameObject enemyPrefab;
public float spawnInterval = 2;
public int maxEnemies = 20;
}
public class SpawnEnemy : MonoBehaviour
{
public GameObject[] waypoints;
public GameObject testEnemyPrefab;
public Wave[] waves;
public int timeBetweenWaves = 5;
private GameManagerBehavior gameManager;
private float lastSpawnTime;
private int enemiesSpawned = 0;
// Use this for initialization
void Start()
{
lastSpawnTime = Time.time;
gameManager =
GameObject.Find("GameManager").GetComponent<GameManagerBehavior>();
}
// Update is called once per frame
void Update()
{
// 1 Get the index of the current wave, and check if it’s the last one.
int currentWave = gameManager.Wave;
if (currentWave < waves.Length)
{
// 2 If so, calculate how much time passed since the last enemy spawn and whether it’s time to spawn an enemy. Here you consider two cases.
// If it’s the first enemy in the wave, you check whether timeInterval is bigger than timeBetweenWaves.
// Otherwise, you check whether timeInterval is bigger than this wave’s spawnInterval. In either case, you make sure you haven’t spawned all the enemies for this wave.
float timeInterval = Time.time - lastSpawnTime;
float spawnInterval = waves[currentWave].spawnInterval;
if (((enemiesSpawned == 0 && timeInterval > timeBetweenWaves) ||
timeInterval > spawnInterval) &&
enemiesSpawned < waves[currentWave].maxEnemies)
{
// 3 If necessary, spawn an enemy by instantiating a copy of enemyPrefab. You also increase the enemiesSpawned count.
lastSpawnTime = Time.time;
GameObject newEnemy = (GameObject)
Instantiate(waves[currentWave].enemyPrefab);
newEnemy.GetComponent<MoveEnemy>().waypoints = waypoints;
newEnemy.GetComponent<MoveEnemy>().JiggleWaypoints();
enemiesSpawned++;
}
// 4 You check the number of enemies on screen. If there are none and it was the last enemy in the wave you spawn the next wave.
// You also give the player 10 percent of all gold left at the end of the wave.
if (enemiesSpawned == waves[currentWave].maxEnemies &&
GameObject.FindGameObjectWithTag("Enemy") == null)
{
gameManager.Wave++;
gameManager.Gold = Mathf.RoundToInt(gameManager.Gold * 1.1f);
enemiesSpawned = 0;
lastSpawnTime = Time.time;
}
// 5 Upon beating the last wave this runs the game won animation.
}
else {
gameManager.gameOver = true;
GameObject gameOverText = GameObject.FindGameObjectWithTag("GameWon");
gameOverText.GetComponent<Animator>().SetBool("gameOver", true);
}
}
}
Second Class
using UnityEngine;
using System.Collections;
public class MoveEnemy : MonoBehaviour
{
[System.NonSerialized]
public GameObject[] waypoints;
private int currentWaypoint = 0;
private float lastWaypointSwitchTime;
public float speed = 1.0f;
// Use this for initialization
void Start()
{
lastWaypointSwitchTime = Time.time;
}
// Update is called once per frame
void Update()
{
// 1
Vector3 startPosition = waypoints[currentWaypoint].transform.position;
Vector3 endPosition = waypoints[currentWaypoint + 1].transform.position;
// 2
float pathLength = Vector3.Distance(startPosition, endPosition);
float totalTimeForPath = pathLength / speed;
float currentTimeOnPath = Time.time - lastWaypointSwitchTime;
gameObject.transform.position = Vector3.Lerp(startPosition, endPosition, currentTimeOnPath / totalTimeForPath);
// 3
if (gameObject.transform.position.Equals(endPosition))
{
if (currentWaypoint < waypoints.Length - 2)
{
// 3.a
currentWaypoint++;
lastWaypointSwitchTime = Time.time;
RotateIntoMoveDirection();
}
else {
// 3.b
Destroy(gameObject);
AudioSource audioSource = gameObject.GetComponent<AudioSource>();
AudioSource.PlayClipAtPoint(audioSource.clip, transform.position);
//<< deduct health
GameManagerBehavior gameManager =
GameObject.Find("GameManager").GetComponent<GameManagerBehavior>();
gameManager.Health -= 1;
//>>
}
}
}
public void JiggleWaypoints()
{
for (int i = 1; i < waypoints.Length; i++)
{
waypoints[i].transform.position = new Vector3(waypoints[i].transform.position.x + Random.Range(-3, 3), waypoints[i].transform.position.y + Random.Range(-3, 3), 0);
}
}
private void RotateIntoMoveDirection()
{
//1 It calculates the bug’s current movement direction by subtracting the current waypoint’s position from that of the next waypoint.
Vector3 newStartPosition = waypoints[currentWaypoint].transform.position;
Vector3 newEndPosition = waypoints[currentWaypoint + 1].transform.position;
Vector3 newDirection = (newEndPosition - newStartPosition);
//2 It uses Mathf.Atan2 to determine the angle toward which newDirection points, in radians, assuming zero points to the right.
// Multiplying the result by 180 / Mathf.PI converts the angle to degrees.
float x = newDirection.x;
float y = newDirection.y;
float rotationAngle = Mathf.Atan2(y, x) * 180 / Mathf.PI;
//3 Finally, it retrieves the child named Sprite and rotates it rotationAngle degrees along the z-axis.
// Note that you rotate the child instead of the parent so the health bar — you’ll add it soon — remains horizontal.
GameObject sprite = (GameObject)
gameObject.transform.FindChild("Sprite").gameObject;
sprite.transform.rotation =
Quaternion.AngleAxis(rotationAngle, Vector3.forward);
}
public float distanceToGoal()
{
float distance = 0;
distance += Vector3.Distance(
gameObject.transform.position,
waypoints[currentWaypoint + 1].transform.position);
for (int i = currentWaypoint + 1; i < waypoints.Length - 1; i++)
{
Vector3 startPosition = waypoints[i].transform.position;
Vector3 endPosition = waypoints[i + 1].transform.position;
distance += Vector3.Distance(startPosition, endPosition);
}
return distance;
}
}
Code is working 100% without errors, BUT....
After each spawn all objects get the same waypoint array. This can be seen on the screen as all objects jump to new waypoint in line together each time new object is spawned. I want the object which is already spawn to live life with it's own array of only once created waypoints.
You need to create a new array of waypoints each time you create one from the prefabricated object. You don't show your Instantiate method but I'm guessing that it has a line like this:
this.waypoints = prefab.waypoints;
This will mean that all object you create will share the same list of waypoints (as you've discovered).
What you need is something like this - assuming that the waypoints have X, Y, and Z properties):
this.waypoints = new GameObject[5];
for (int i = 0; i++ ; i < 5)
{
this.waypoints[i].X = prefab.waypoints[i].X;
this.waypoints[i].Y = prefab.waypoints[i].Y;
this.waypoints[i].Z = prefab.waypoints[i].Z;
}
(If you want your points to be a variable length you might want to consider using a list).
This means that each object has a list of unique points even if they start with the same values you can change each independently.
Based on ChrisFs' and Joe Blows' answers, do something like this in your MoveEnemy script:
private Vector3[] myWay;
public void JiggleWaypoints(GameObject[] waypoints)
{
myWay = new Vector3[waypoints.Length];
for(int i = 1; i < waypoints.Length; i++)
{
myWay[i] = new Vector3(waypoints[i].transform.position.x + Random.Range(-3, 4), waypoints[i].transform.position.y + Random.Range(-3, 4), 0);
}
}
myWay replaces the GameObject[].
In your SpawnEnemy script you do this:
GameObject e = (GameObject)Instantiate(enemyPrefab);
e.GetComponent<MoveEnemy>().JiggleWaypoints(waypoints);

Categories