C# How to make an object move toward in a circular way

Hello everyone,

am trying to make the enemies follow the player and the same time move in circle with a random radius, you may wanna take a look to this example cause that’s exactly what am trying to make but it seems like all what i know in 2D development doesn’t work in unity :stuck_out_tongue:
so can you please set me in the right path

1 Like

This isn’t tested, and it is rather simple, but would probably mimic the behavior in your link to some degree:

	public GameObject target;
	public float movementSpeed = 5f;
	public float rotationSpeed = 90f;
	
	// Use this for initialization
	void Start () {
		transform.LookAt(target.transform);
	}
	
	// Update is called once per frame
	void Update () {
		
		transform.position += transform.forward * movementSpeed * Time.deltaTime;
		transform.rotation = Quaternion.RotateTowards(transform.rotation, Quaternion.LookRotation(target.transform.position - transform.position), rotationSpeed * Time.deltaTime);
		
	}

The approach is to move the object ‘forward’ each frame, and to turn smoothly and over time towards the target. @whebert’s approach is in the right direction for objects in 3D space. The example game was 2D, which requires a bit different code for rotation and movement.

using UnityEngine;
using System.Collections;
 
public class Seeker : MonoBehaviour {
 
	public float minRotationSpeed = 80.0f;
	public float maxRotationSpeed = 120.0f;
	public float minMovementSpeed = 1.75f;
	public float maxMovementSpeed = 2.25f;
	private float rotationSpeed = 75.0f; // Degrees per second
	private float movementSpeed = 2.0f; // Units per second;
    private Transform target;
	private Quaternion qTo;
	
	void Start() {
		target = GameObject.Find ("Player").transform;	
		rotationSpeed = Random.Range (minRotationSpeed, maxRotationSpeed);
		movementSpeed = Random.Range (minMovementSpeed, maxMovementSpeed);
	}
	
	void Update() {
		Vector3 v3 = target.position - transform.position;
		float angle = Mathf.Atan2(v3.y, v3.x) * Mathf.Rad2Deg;
		qTo = Quaternion.AngleAxis (angle, Vector3.forward);
		transform.rotation = Quaternion.RotateTowards (transform.rotation, qTo, rotationSpeed * Time.deltaTime);
		transform.Translate (Vector3.right * movementSpeed * Time.deltaTime);
	}
}

I’ve included a range for rotation speed and movement speed. This will help give the enemies some separation. The above code is expected to be put on a vertical plane such as the ones that can be created by the CreatePlane editor script on the Unity Wiki. It expects the ‘front’ to be the right side of the texture on the plane.