- Home /
Question by
sf27blll · Mar 01 at 03:18 PM ·
colliderscript.characterscripting beginner
Collecting objects for limited time after colliding magnet, how can i do that?,
Hello guys, I have a script in my game that I want to run when the character collides the magnet in the level. Currently, the character is pulling all objects without colliding the magnet. I also want character to attract objects for 5-10 seconds after colliding the magnet. How can i do that?
https://youtu.be/MnxcAajbCCs this is the game i am working on.
This is the script code below so this script should work only when i collide with magnet. Magnet must work for 5-10 second then this script shouldn't work again.
using System.Collections.Generic;
using UnityEngine;
public class CoinsController : MonoBehaviour
{
[SerializeField]
private int numberOfCoins;
[SerializeField]
private float radius;
[SerializeField]
private string coinTag;
[SerializeField]
private float pickupSpeed;
[SerializeField]
private float pickupDistance;
private List<Transform> coins;
void Start()
{
coins = new List<Transform>();
}
void FixedUpdate()
{
Collider[] hitColliders = Physics.OverlapSphere(transform.position, radius);
for (int i = 0; i < hitColliders.Length; i++)
{
if (hitColliders[i].CompareTag(coinTag) &&
!coins.Contains(hitColliders[i].transform))
{
coins.Add(hitColliders[i].transform);
}
}
for (int i = 0; i < coins.Count; i++)
{
if (Vector3.Distance(transform.position, coins[i].position) <= pickupDistance)
{
numberOfCoins += 1;
coins[i].gameObject.SetActive(false);
coins.Remove(coins[i]);
}
else
{
float step = pickupSpeed * Time.deltaTime;
coins[i].position = Vector3.MoveTowards(coins[i].position, transform.position, step);
}
}
}
}
Comment