using System.Collections; using System.Collections.Generic; using UnityEngine; public class RandomRectangle2D : MonoBehaviour { public float moveSpeed = 1f; public float SpeedOfChangingTarget = 5f; public float height = 10f; public float width = 10f; public float circleRadious = 0.5f; Vector3 target; Vector3 startPos; void Start() { InvokeRepeating("GenerateNewTarget", 0f, SpeedOfChangingTarget); startPos = transform.position; } void FixedUpdate() { Vector3 currentPos = transform.position; if (currentPos == target) { GenerateNewTarget(); } transform.position = Vector3.MoveTowards(currentPos, target, Time.deltaTime * moveSpeed); //movement from current position to target position } void OnCollisionStay2D() { GenerateNewTarget(); } void GenerateNewTarget() { target = new Vector3(Random.Range(-(width / 2 - circleRadious), width / 2 - circleRadious) + startPos.x, Random.Range(-(height / 2 - circleRadious), height / 2 - circleRadious) + startPos.y, 0); //again provide random position in x and y } }