Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System.Collections.Generic;
- using UnityEngine;
- public class Movement : MonoBehaviour
- {
- [SerializeField] private float _speed;
- [SerializeField] private Transform _target;
- [SerializeField] private Transform _prefab;
- private Vector2 TargetDirection => (_target.position - transform.position).normalized;
- private void Update()
- {
- Vector2 roundDirection = GetDirectionAlongCircle();
- float weight = GetWeight();
- Vector3 finalDirection = (1 - weight) * roundDirection + weight * TargetDirection;
- transform.position += finalDirection.normalized * Time.deltaTime * _speed;
- //Instantiate(_prefab, transform.position, Quaternion.identity);
- }
- private float GetWeight()
- {
- float t = Mathf.InverseLerp(2, 4, Vector3.Distance(transform.position, _target.position));
- float weight = Mathf.Lerp(0, 1, t);
- return weight;
- }
- private Vector2 GetDirectionAlongCircle()
- {
- Vector2 r = transform.position - _target.position;
- float angle = GetRotationAngle(r.magnitude, Time.deltaTime * _speed);
- Vector2 rotatedR = RotateVector(r, angle);
- Vector2 roundDirection = (rotatedR - r).normalized;
- return roundDirection;
- }
- private Vector2 RotateVector(Vector2 vector, float rad)
- {
- Vector2 right = new Vector2(Mathf.Cos(rad), Mathf.Sin(rad));
- Vector2 up = new Vector2(-Mathf.Sin(rad), Mathf.Cos(rad));
- return new Vector2(right.x * vector.x + up.x * vector.y,
- right.y * vector.x + up.y * vector.y);
- }
- private float GetRotationAngle(float r, float chord) =>
- Mathf.Asin(chord / (2 * r)) * 2;
- }
Advertisement
Add Comment
Please, Sign In to add comment