Home > OS >  How to add the follow target to my Cos and Sin?
How to add the follow target to my Cos and Sin?

Time:01-24

How do I use Cos and Sin animation, and at the same time follow the target(Player)? I'm not seeing how to do that. I'm a beginner in programming.

public class Spirit : MonoBehaviour
{
    //target player
    private bool isFollowing;

    public float followSpeed;
    public Transform followTarget;

    //Sin & Con animation
    [SerializeField] private float frequency;
    [SerializeField] private float amplitude;
    [SerializeField] private float _frequency;
    [SerializeField] private float _amplitude;

    private void FixedUpdate()
    {
        if (isFollowing)
        {
            //This is used to follow the player
            transform.position = Vector3.Lerp(transform.position, followTarget.position, followSpeed * Time.deltaTime);
            
            //This is the animation with Cos and Sin.
            float x = Mathf.Cos(Time.time * _frequency) * _amplitude;
            float y = Mathf.Sin(Time.time * frequency) * amplitude;
            float z = transform.position.z;

            transform.position = new Vector3(x, y, z);
        }
    }
}

Making a spirit ball follow the player and animating it using Cos and Sin using the frequency and amplitude of both X and Y coordinates.

CodePudding user response:

Your code is actually very close but you are overwriting the transform.position later so your previous lerp is not working. Just include your cos and sin calculations while you are handling the lerp. Here is how you can modify your code to make it work.

//target player
private bool isFollowing = true; // for testing

[SerializeField] private float _followSpeed = 1f;
[SerializeField] private Transform _followTarget;

//Sin & Con animation
[SerializeField] private float _frequency = 1f;
[SerializeField] private float _amplitude = 1f;

private void Update()
{
    if (!isFollowing) return;
    // including cos to target position.x and sin to target position.y
    Vector3 targetPosition = new Vector3(_followTarget.position.x   Mathf.Cos(Time.time * _frequency) * _amplitude,
        _followTarget.position.y   Mathf.Sin(Time.time * _frequency) * _amplitude,
        _followTarget.position.z);
    //now put above calculation into lerp
    transform.position = Vector3.Lerp(transform.position, targetPosition, _followSpeed * Time.deltaTime);
}
  • Related