Write unity code to move 2d sprite in a circle with variable speed control and activator…
- User
Write unity code to move 2d sprite in a circle with variable speed control and activator through a serialized field using unirx
- Assistant
Here's a simple Unity script using UniRx that allows you to move a 2D sprite in a circle with variable speed control and an activator through a serialized field. This script should be attached to the GameObject with the sprite renderer and a collider.
csharpusing UnityEngine; using UniRx; public class CircleMover : MonoBehaviour { [SerializeField] private float speed = 1.0f; [SerializeField] private bool isActive = true; private float angle = 0.0f; private Vector3 center; private void Start() { center = transform.position; Observable.EveryUpdate() .Where(_ => isActive) .Subscribe(_ => MoveInCircle()) .AddTo(this); } private void MoveInCircle() { angle += speed * Time.deltaTime; var offset = new Vector2(Mathf.Cos(angle), Mathf.Sin(angle)) * 1.0f; transform.position = center + offset; } }In this script, you can control the speed of the sprite movement using the
speedvariable and activate/deactivate the movement using theisActivevariable. Both variables are serialized fields, so you can modify them in the Unity editor.The
MoveInCirclemethod updates the sprite's position based on the angle and speed. The angle is incremented every frame, and the new position is calculated using the cosine and sine of the angle. TheObservable.EveryUpdate()method from UniRx is used to call theMoveInCirclemethod every frame. - User
add distance offset from the origin and make all variables private and serialized
- Assistant
Here's the updated script with the distance offset from the origin and all variables made private and serialized:
csharpusing UnityEngine; using UniRx; public class CircleMover : MonoBehaviour { [SerializeField] private float speed = 1.0f; [SerializeField] private bool isActive = true; [SerializeField] private float distanceFromOrigin = 1.0f; private float angle = 0.0f; private Vector3 center; private void Start() { center = transform.position; Observable.EveryUpdate() .Where(_ => isActive) .Subscribe(_ => MoveInCircle()) .AddTo(this); } private void MoveInCircle() { angle += speed * Time.deltaTime; var offset = new Vector2(Mathf.Cos(angle), Mathf.Sin(angle)) * distanceFromOrigin; transform.position = center + offset; } }
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.