I am developing a game where the main character constantly moves at a certain speed and collects coins.
When the coins are collected, an animation(DOTween) moves them to a text that displays the total number of fixed coins on the screen
Vector3 targetPosition = Transform target.position
However, since the character and the background are constantly moving forward, the coins end up going behind the target position. How can i solve this problem ?
Although I tried solutions like FixedUpdate
-Update
, it didn’t work.
Can you help me with this?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;
using DG.Tweening;
using System.Collections.Generic;
public class CoinCounter : MonoBehaviour
{
[Header("UI reference")]
[SerializeField] TMP_Text coinUIText;
[SerializeField] GameObject animatedCoinPrefab;
[SerializeField] Transform target;
[Space]
[Header("Available coins : (coins to pool )")]
[SerializeField] int maxCoins;
Queue<GameObject> coinsQueue = new Queue<GameObject>();
[Space]
[Header("Animation settings ")]
[SerializeField] [Range(0.5f,0.9f)] float minAnimDuration;
[SerializeField] [Range(0.9f,2f)] float maxAnimDuration;
[SerializeField] Ease easeType;
Vector3 targetPosition;
private int _c = 0;
public int Coins
{
get{return _c;}
set{
_c = value;
//update UI text whenever "Coins" variable is changeds
coinUIText.text = Coins.ToString();
}
}
void FixedUpdate()
{
targetPosition = target.position;
//prepare pool
PrepareCoins();
}
void PrepareCoins()
{
GameObject coin;
for(int i = 0; i<maxCoins; i++)
{
coin = Instantiate(animatedCoinPrefab);
coin.transform.parent = transform;
coin.SetActive(false);
coinsQueue.Enqueue(coin);
}
}
void Animate(Vector3 collectedCoinPosition, int amount)
{
for(int i = 0; i<amount; i++)
{
//check if there's coins in the pool
if(coinsQueue.Count > 0)
{
//extract a coin from the pool
GameObject coin = coinsQueue.Dequeue();
coin.SetActive(true);
//move coin to the collected coin pos
coin.transform.position = collectedCoinPosition;
//animate coin to target position
float duration = Random.Range(minAnimDuration,maxAnimDuration);
Vector3 initialPosition = collectedCoinPosition;
Vector3 targetOffset = targetPosition - initialPosition;
coin.transform.DOMove(targetPosition + targetOffset,duration).SetEase(easeType).OnComplete(()=>
{
//execute whenever coin reach target position
coin.SetActive(false);
coinsQueue.Enqueue(coin);
Coins++;
});
}
}
}
public void AddCoins(Vector3 collectedCoinPosition, int amount)
{
Animate(collectedCoinPosition,amount);
}
// Update is called once per frame
void OnTriggerEnter2D(Collider2D other)
{
}
}