Make circular moving object stay within a specific area
Hello, Currently I have successfully implemented an enemy that can moving in a circular motion, however, when I begin the game the enemy goes off to a completely random area of the level. How would I ensure that the enemy stays within a specific area while moving circular? Thank you.
 using UnityEngine;
 using System.Collections;
 
 public class CircularMovement : MonoBehaviour {
 
     //timer
     float timeCounter = 0;
 
     //speed
     public float speed;
     public float width;
     public float height;
 
     // Use this for initialization
     private void Start () {
         speed = 2;
         width = 2;
         height = 3;
 
         //start in positon 
         transform.position = new Vector3(53.939f, 1.201f);
         transform.position = transform.position;
 
     }
     
     // Update is called once per frame
     void Update () {
         timeCounter += Time.deltaTime*speed;
 
         //directional path
         float x = Mathf.Cos (timeCounter)*width;
         float y = Mathf.Sin (timeCounter)*height;
 
 
         transform.position = new Vector2(x, y);
     
     }
 }
 
 
              If you want the enemy to move around in a fixed area , why not use unity's API function Transform.RotateAround..
https://docs.unity3d.com/ScriptReference/Transform.RotateAround.html
Answer by Dre0 · Feb 09, 2017 at 08:45 PM
Hi I tried using the following function and ensuring that I placed the game object correctly but for some reason it still will not work. Any suggestions?
  void OrbitAround()
     {
         transform.RotateAround(Boundary.transform.position, Vector2.right, 3 * Time.deltaTime);
     }
 
              Change your orbitAround to something like the following , and make sure the object to which this script is attached is at a distance (away) from the 'point' around which it rotates :
     public Transform point;
 
     // Update is called once per frame
     void Update () {
     
         OrbitAround();
     }
 
     void OrbitAround()
     {
         transform.RotateAround(point.position, Vector3.up, 10 * Time.deltaTime);
     }
 
                  Just as in this screenshot the point(sphere) is at the centre and the Cube is the object to which this script is applied.
Your answer
 
             Follow this Question
Related Questions
Help with a health bar 0 Answers
Enemy AI ignores the distance from the player 0 Answers
How to tidy up my code for Unity 5 Basic Platformer 1 Answer