DayTransition working properly again

Animals now move randomly (but they never stop moving)
This commit is contained in:
d-hain 2022-06-16 14:41:24 +02:00
parent 3a564aa909
commit 687a37eb89
8 changed files with 51 additions and 60 deletions

View file

@ -1,41 +1,41 @@
using System;
using System.Collections;
using DefaultNamespace;
using UnityEngine;
using Random = UnityEngine.Random;
public class Animal : MonoBehaviour {
private Item _producedItem;
private Rigidbody2D _rigidbody;
public Item ProducedItem => _producedItem;
public Item producedItem;
public Sprite animalSprite;
public int movementSpeed;
private void Start() {
_rigidbody = gameObject.GetComponent<Rigidbody2D>();
animalSprite = gameObject.GetComponent<SpriteRenderer>().GetComponent<Sprite>();
}
private void Update() {
_rigidbody.rotation = 0f;
Vector2 direction = new Vector2(
Random.Range(-1f, 1f),
Random.Range(-1f, 1f));
direction.Normalize();
_rigidbody.velocity = movementSpeed * direction;
// Move the Animal in any random direction every 1-5s
InvokeRepeating(nameof(MoveInRandomDirection), 2f, Random.Range(1f, 5f));
}
private void OnCollisionEnter2D(Collision2D col) {
Vector2 oldPos = _rigidbody.position;
//TODO: collide with edges working but no stopping
string[] colNames = { "Top", "Bottom", "Left", "Right" };
foreach(string colName in colNames) {
if(colName.ToUpper().Equals(col.gameObject.name.ToUpper())) {
Debug.Log("EEEEEEEE " + col.gameObject.name);
_rigidbody.position = oldPos;
}
}
// Moves the Animal in any random direction for a random amount of time
private void MoveInRandomDirection() {
IEnumerator Move() {
float randTime = Random.Range(0.5f, 1f);
_rigidbody.rotation = 0f;
Vector2 direction = new Vector2(
Random.Range(-1f, 1f),
Random.Range(-1f, 1f));
direction.Normalize();
_rigidbody.velocity = movementSpeed * direction;
StopAllCoroutines();
yield return new WaitForSeconds(randTime);
_rigidbody.velocity = new Vector2(0f, 0f); }
StartCoroutine(Move());
}
// TODO: Animations