Unity 2D - Moving Any Object Between Two (or more) Spaces - c#

new Unity person, and new coder in general. I'm trying to have an object move back and forth between two spots. I have it right now going from Point 1 to Point 2, but it stops. I tried a do loop, and to call back the Move() function again but it just froze Unity.
I'm guessing I need some sort of Loop, but not sure where to do it? I wouldn't mind having the ability to add more spots as well. I have waypoints in Unity itself, tied to the Object. Thanks!
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ZombiePathing : MonoBehaviour
{
[SerializeField] List<Transform> waypoints;
[SerializeField] float moveSpeed = 2f;
int waypointIndex = 0;
void Start()
{
transform.position = waypoints[waypointIndex].transform.position;
}
// Update is called once per frame
void Update()
{
Move();
}
private void Move()
{
if (waypointIndex <= waypoints.Count -1)
{
var targetPosition = waypoints[waypointIndex].transform.position;
var movementThisFrame = moveSpeed * Time.deltaTime;
transform.position = Vector2.MoveTowards
(transform.position, targetPosition, movementThisFrame);
if (transform.position == targetPosition)
{
waypointIndex++;
}
}
}
}

just add an index equal to 1 or -1 depends on the current transform,
I wrote this code very quickly so it's unsorted, and I do my best to make it very close to your code with some edits.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ZombiePathing : MonoBehaviour
{
[SerializeField] List<Transform> waypoints;
[SerializeField] float moveSpeed = 2f;
Vector3 targetPosition;
int waypointIndex = 0;
int index = 1;
void Start()
{
transform.position = waypoints[waypointIndex].position;
UpdateTransform();
}
void Update()
{ transform.position = Vector2.MoveTowards
(transform.position, targetPosition, moveSpeed * Time.deltaTime);
if (transform.position == targetPosition) UpdateTransform();
}
private void UpdateTransform()
{
waypointIndex += index;
targetPosition = waypoints[waypointIndex].position;
if (waypointIndex >= waypoints.Count -1) index = -1;
else if (waypointIndex <= 0 && index == -1)index = 1;
}
}

Related

How to make an object move endlessly?

I want to move an object from position A to position B on X axis endlessly. But it does move and comeback only once. How to make it continuosly? I've tried Vector3.Lerp or just creating new Vector3 but it only teleports.
`
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MovingTarget : MonoBehaviour
{
[SerializeField] private Vector3 firstPosition = new Vector3(-14f, 2.5f, 17f);
[SerializeField] private Vector3 secondPosition = new Vector3(14f, 2.5f, 17f);
public float speed = 10f;
void Start()
{
transform.position = firstPosition;
}
void Update()
{
transform.position = Vector3.MoveTowards(transform.position, secondPosition, Time.deltaTime * speed);
if(transform.position == secondPosition)
{
secondPosition = firstPosition;
}
}
}
`
As alternative you could also use Mathf.PingPong like e.g.
// By default afaik a full cycle takes 2 seconds so in order to normalize
// this to one second we will divide by this times 2 later
public float cycleDuration = 1;
private void Update ()
{
transform.position = Vector3.Lerp(firstPosition, secondPosition, Mathf.PingPong(Time.time / (cycleDuration * 2f), 1f));
}
In case your object is spawned later in the game you might want to rather always start at the first position and do
private float timer;
private void Update ()
{
transform.position = Vector3.Lerp(firstPosition, secondPosition, Mathf.PingPong(timer / (cycleDuration * 2f), 1f));
timer += Time.deltaTime;
}
I don't use Unity, but since nobody else answered....
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MovingTarget : MonoBehaviour
{
[SerializeField] private Vector3 firstPosition = new Vector3(-14f, 2.5f, 17f);
[SerializeField] private Vector3 secondPosition = new Vector3(14f, 2.5f, 17f);
private Vector3 target;
public float speed = 10f;
void Start()
{
transform.position = firstPosition;
target = secondPosition;
}
void Update()
{
transform.position = Vector3.MoveTowards(transform.position, target, Time.deltaTime * speed);
if (transform.position == firstPosition)
{
target = secondPosition;
}
else if (transform.position == secondPosition)
{
target = firstPosition;
}
}
}

Unity 2d : Objects being reinstantiated on scene reload after being destroyed

GOAL
So I'm creating a top down arena battler type game, and I want you to be able to restart the game by pressing R.
PROBLEM
When I press R, the whole scene resets as it should, except all the enemies that were previously instantiated (and then destroyed) are spawned again, all at once.
CODE
This is the enemy spawning code :
using System.Collections.Generic;
using UnityEngine;
public class EnemySpawn : MonoBehaviour
{
private float nextActionTime = 0.0f;
public float period = 5f;
public GameObject enemy;
void Update()
{
if (Time.time > nextActionTime ) {
nextActionTime += period;
GameObject clone = Instantiate(enemy, new Vector3(-1, 3, 0), Quaternion.identity);
clone.tag = "enemy";
}
}
}
This is the player code, responsible for restarting the scene (I have marked what I belive to be the relevantant sections with dashes) :
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
public class PlayerController : MonoBehaviour
{
public Rigidbody2D rb;
public GameObject Shield;
public GameObject ShieldInstance;
public float moveSpeed = 4.3f;
public float sheildSpeed = 5f;
Vector2 movement;
AudioSource woop;
AudioSource waa;
----------------------------
GameObject[] enemies;
----------------------------
bool isDead = false;
void Start() {
woop = GameObject.Find("Main Camera/ShieldSFX").GetComponent<AudioSource>();
waa = GameObject.Find("Main Camera/DefeatSFX").GetComponent<AudioSource>();
}
void Update()
{
--------------------------------------------------------------
enemies = GameObject.FindGameObjectsWithTag("enemy");
--------------------------------------------------------------
movement.x = Input.GetAxisRaw("Horizontal");
movement.y = Input.GetAxisRaw("Vertical");
Vector3 mouseScreen = Input.mousePosition;
Vector3 mouse = Camera.main.ScreenToWorldPoint(mouseScreen);
transform.rotation = Quaternion.Euler(0, 0, Mathf.Atan2(mouse.y - transform.position.y, mouse.x - transform.position.x) * Mathf.Rad2Deg - 90);
if (Input.GetMouseButtonDown(0))
{
if (ShieldInstance != null || transform.GetChild(0).GetComponent<SpriteRenderer>().enabled == false) { return; }
woop.Play();
ShieldInstance = Instantiate(Shield, transform.position + transform.forward + transform.up, transform.rotation);
ShieldInstance.transform.parent = transform;
}
if (Input.GetMouseButtonUp(0))
{
if (ShieldInstance == null) { return; }
ShieldInstance.transform.parent = null;
ShieldInstance.GetComponent<ShieldController>().LaunchForward(sheildSpeed);
Destroy(ShieldInstance, 2.3f);
}
-------------------------------------------------------------------------------
if (Input.GetKey("r")) {
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
foreach (GameObject one in enemies) {
Destroy(one);
}
}
-------------------------------------------------------------------------------
}
void FixedUpdate() {
if (!isDead) {
rb.MovePosition(rb.position + movement * moveSpeed * Time.fixedDeltaTime);
}
}
void OnCollisionEnter2D(Collision2D other) {
if (other.gameObject.tag == "enemy") {
waa.Play();
GameObject.Find("Canvas/gameover").GetComponent<Text>().enabled = true;
transform.GetChild(0).GetComponent<SpriteRenderer>().enabled = false;
GetComponent<PolygonCollider2D>().enabled = false;
}
}
}
And this is the enemy code :
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyFollow : MonoBehaviour
{
public float moveSpeed;
public ParticleSystem explode;
AudioSource boom;
Vector2 movement;
GameObject player;
Rigidbody2D rb;
SpriteRenderer sr;
PolygonCollider2D pc;
void Start() {
rb = GetComponent<Rigidbody2D>();
sr = transform.GetChild(0).GetComponent<SpriteRenderer>();
pc = GetComponent<PolygonCollider2D>();
player = GameObject.Find("Player");
boom = GameObject.Find("Main Camera/ExplodeSFX").GetComponent<AudioSource>();
}
void Update()
{
Vector2 difference = (player.transform.position - new Vector3(2, .5f, 0)) - transform.position;
if (difference.x > 0) {
movement.x = 1;
} else if (difference.x < 0){
movement.x = -1;
} else {
movement.x = 0;
}
if (difference.y > 0) {
movement.y = 1;
} else if (difference.y < 0){
movement.y = -1;
} else {
movement.y = 0;
}
rb.MovePosition(rb.position + movement * moveSpeed * Time.fixedDeltaTime);
}
void OnCollisionEnter2D(Collision2D other) {
if (other.gameObject.tag == "shield") {
StartCoroutine(ExplodeF());
}
}
private IEnumerator ExplodeF() {
explode.Play();
boom.Play();
sr.enabled = false;
pc.enabled = false;
yield return new WaitForSeconds(explode.main.startLifetime.constantMax);
Destroy(gameObject);
}
}
I would really appreciate any help!
If you want / need more details, just leave a comment :)
The problem is in Time.time, it is time since the start of the application, not since the start of the scene. So if you were in the game 30 secs, Time.time is 30 secs. If you reload the scene it is still 30 secs.
You have to count the time passed since entering the scene. Then it won't respawn all the enemies on scene reload.
When you restart the scene, everything is being destroyed and reset back except for the time.
The problem in your code is in the enemy spawner. Time.time returns the time passed since you started the game (and not since the scene was loaded). So, after the restart the if condition is true and the enemies are spawned.
If you want to count the time (in seconds) since the scene was loaded, what you can do is to add a variable in the enemy spawner class that would count the time
using System.Collections.Generic;
using UnityEngine;
public class EnemySpawn : MonoBehaviour
{
private float nextActionTime = 0.0f;
private float timeSinceStart = 0;
public float period = 5f;
public GameObject enemy;
void Update()
{
if (timeSinceStart > nextActionTime ) {
nextActionTime += period;
GameObject clone = Instantiate(enemy, new Vector3(-1, 3, 0), Quaternion.identity);
clone.tag = "enemy";
}
timeSinceStart += Time.deltaTime;
}
}
See Time.deltaTime

How can I move a cube between other targets in different ways between each one?

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MovementSpeedController : MonoBehaviour
{
public Transform[] targets;
public float speed = 1f;
public Vector3 velocity = Vector3.zero;
private void Start()
{
}
private void Update()
{
transform.position = Vector3.Lerp(transform.position,
targets[0].position, speed * Time.deltaTime);
if (transform.position == targets[0].position)
{
transform.position = Vector3.MoveTowards(transform.position,
targets[1].position, speed * Time.deltaTime);
}
if (transform.position == targets[1].position)
{
transform.position = Vector3.SmoothDamp(transform.position,
targets[2].position, ref velocity, speed * Time.deltaTime);
}
}
}
The script is attached to a cube the cube should move between 3 other cubes each cube in another positions. and I want that the transform will move to the first target using lerp then movetowards and then to the last cube using smoothdamp to show all the movements.
The problem is how to do it without manually type each target index 0,1,2 ? and how to move it between them because now this is true :
transform.position == targets[0].position
but it's not moving to the next cube.
Tried this :
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MovementSpeedController : MonoBehaviour
{
public Transform[] targets;
public float speed = 1f;
public Vector3 velocity = Vector3.zero;
private int targetIndex = 0;
private void Start()
{
}
private void Update()
{
var targetPosition = targets[targetIndex];
if (targetIndex == 0)
{
transform.position = Vector3.Lerp(transform.position,
targetPosition.position, speed * Time.deltaTime);
}
if(transform.position == targetPosition.position)
{
targetIndex++;
transform.position = Vector3.MoveTowards(transform.position,
targets[1].position, speed * Time.deltaTime);
}
}
}
Add a variable for targetIndex, initialize it to zero, and each time you reach the target increase that index. Use that index in your targets array.
targetPosition = targets[targetIndex];
You can also use that index to figure out which movement type you need to use.
if (targetIndex == 0) // do lerp or in a switch case
Here is an example.
private Vector3 startingPosition = Vector3.zero;
private int targetIndex = 0;
private float lerpT = 0;
void Start()
{
targetIndex = -1;
SetNextTarget();
}
void Update()
{
switch (targetIndex)
{
case 0: UpdateLerp(); break;
case 1: UpdateMoveTowards(); break;
case 2: UpdateSmoothDamp(); break;
}
}
void UpdateLerp()
{
lerpT += Time.deltaTime * speed;
if (lerpT > 1)
lerpT = 1;
transform.position = Vector3.Lerp(startingPosition, target, lerpT);
if (lerpT == 1)
{
SetNextTarget();
}
}
void UpdateMoveTowards()
{
transform.position = Vector3.MoveTowards(transform.position, target, speed * Time.deltaTime);
if (Vector3.Distance(transform.position, target) <= Mathf.Epsilon)
{
SetNextTarget();
}
}
void UpdateSmoothDamp()
{
// Using the examples, fill in this one with the smooth damp version of movement
}
void SetNextTarget()
{
targetIndex++;
target = targets[targetIndex];
startingPosition = transform.position;
}

How To randomize timer duration between two floats

Currently, This code spawns my prefab with only 1 float aka 1 second or w.e. I'm wanting to spawn my prefab between a minimum float and maximum float but not sure what to do because I'm novice and still learning c# and unity.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Spawn : MonoBehaviour
{
[SerializeField]
public GameObject coin;
[SerializeField]
float fTimeIntervals;
[SerializeField]
Vector2 v2SpawnPosJitter;
float fTimer = 0;
public CurrencyManager cm;
// Start is called before the first frame update
void Start()
{
fTimer = fTimeIntervals;
}
// Update is called once per frame
void Update()
{
fTimer -= Time.deltaTime;
if (fTimer <= 0)
{
fTimer = fTimeIntervals;
Vector2 v2SpawnPos = transform.position;
v2SpawnPos += Vector2.right * v2SpawnPosJitter.x * (Random.value - 0.5f);
v2SpawnPos += Vector2.up * v2SpawnPosJitter.y * (Random.value - 0.5f);
GameObject cmscript = Instantiate(coin, v2SpawnPos, Quaternion.identity, GameObject.FindGameObjectWithTag("Canvas").transform);
cmscript.GetComponent<AutoDestroy>().CM = cm;
}
}
}
Split your fTimeIntervals field into a fMaxTimeInterval field and a fMinTimeInterval field then use Random.Range when you reset the timer to set it to a value between those intervals. You can even make a ResetTimer method to do this in Start and Update so if you change how you do it, you only have to change it in one place:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Spawn : MonoBehaviour
{
[SerializeField]
public GameObject coin;
[SerializeField]
float fMinTimeInterval;
[SerializeField]
float fMaxTimeInterval;
[SerializeField]
Vector2 v2SpawnPosJitter;
float fTimer = 0;
public CurrencyManager cm;
// Start is called before the first frame update
void Start()
{
ResetTimer();
}
// Update is called once per frame
void Update()
{
fTimer -= Time.deltaTime;
if (fTimer <= 0)
{
ResetTimer();
Vector2 v2SpawnPos = transform.position;
v2SpawnPos += Vector2.right * v2SpawnPosJitter.x * (Random.value - 0.5f);
v2SpawnPos += Vector2.up * v2SpawnPosJitter.y * (Random.value - 0.5f);
GameObject cmscript = Instantiate(coin, v2SpawnPos, Quaternion.identity, GameObject.FindGameObjectWithTag("Canvas").transform);
cmscript.GetComponent<AutoDestroy>().CM = cm;
}
}
void ResetTimer()
{
fTimer = Random.Range(fMinTimeInterval,fMaxTimeInterval);
}
}
Didn't really understand what you meant, did you mean the timer?
Use random.range if you want a random number between min/max value
https://docs.unity3d.com/ScriptReference/Random.Range.html

How can i make my prefab completely reverse (180 degrees) from it's spawnpoint? Unity 2D

So i made a little side scroller that uses a prefab to spawn bullets.
My problem is that it only shoots to one side... the Right.
I need it to fire to the left as well. I've already made a variable to see if the player is looking to the right or left.
I've tried to put the Speed to -20 and i've tried to rotate it 180 degrees on it's Z axis. I tested if the bullet script even picked up the change from the player movement script and it does.
Player Movement script
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
public GameObject bullet;
private Rigidbody2D myRigidbody;
private float speed = 15;
private bool facingRight;
private bool ground = false;
private float jump = 23;
// Start is called before the first frame update
void Start()
{
facingRight = true;
myRigidbody = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void FixedUpdate()
{
float horizontal = Input.GetAxis("Horizontal");
Movement(horizontal);
Flip(horizontal);
if (Input.GetKey("w"))
{
if (ground)
{
GetComponent<Rigidbody2D>().velocity = new Vector2(GetComponent<Rigidbody2D>().velocity.x, jump);
}
}
if(facingRight == false)
{
bullet.GetComponent<bullet>().left = true;
}
if (facingRight == true)
{
bullet.GetComponent<bullet>().left = false;
}
}
void OnTriggerEnter2D()
{
ground = true;
}
void OnTriggerExit2D()
{
ground = false;
}
private void Movement(float horizontal)
{
myRigidbody.velocity = new Vector2(horizontal * speed,myRigidbody.velocity.y);
}
private void Flip(float horizontal)
{
if (horizontal > 0 && !facingRight || horizontal < 0 && facingRight)
{
facingRight = !facingRight;
Vector3 theScale = transform.localScale;
theScale.x *= -1;
transform.localScale = theScale;
}
}
}
Weapon script
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class weapon : MonoBehaviour
{
// Start is called before the first frame update
public bool right;
public Transform firepointR;
public GameObject bulletPrefab;
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown("space"))
{
Debug.Log("Oh well");
Shoot();
}
}
void Shoot()
{
Instantiate(bulletPrefab, firepointR.position, firepointR.rotation);
}
}
bullet script
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class bullet : MonoBehaviour
{
public bool left;
public float speed = 20;
public Rigidbody2D rb;
// Start is called before the first frame update
void Start()
{
rb.velocity = transform.right * speed;
}
// Update is called once per frame
void FixedUpdate()
{
Debug.Log(speed);
if (left == false)
{
transform.Rotate(0, 0, 180);
}
}
}
As i previously said i need my bullet (prefab) to go the opposite direction but whatever i do right now it will always go right.
Expanding on my comment:
Did you try reversing the velocity?
rb.velocity = -(transform.right * speed);
Note: There are instances when using a negative float wont return the opposite of the positive result. However, in this example, it will work just fine.
I imagine this will work also (and is probably the correct way of doing it):
rb.velocity = transform.left * speed;

Categories

Resources