magnetic powerup (pulling coins towards character)

hi guys i m trying to make power up like in subway surfer or temple run MAGNET one.
when ever character picks up the magnet powerup i want my character to pull the coins near by him.
how can i achieve this one any help would be great.

tks a lot in advance.
:slight_smile:

if(Vector3.Distance(transform.position, player.position) < dist)
{
      transform.position = Vector3.MoveTowards(transform.position, player.position, Time.deltaTime * coinSpeed);
}

The vector3 distance check if we a within a given range, if we are we use interpolation to move towards our player at a given speed (coinSpeed). Just make sure that the coin is faster than the player.

:wink:

Lots of coins checking Distance every frame could be expensive. Attaching triggers and using OnTriggerEnter() on the coins could be a cheaper option.

I am not sure that collision checks will be cheaper.

well, im guessing the quickest way is simply to use Physics.OverlapSphere and then just check if the object is indeed a coin

hi guys i did something like this when i gets magnet power up my coins collider get bigger in radius and when ever character enters the sphere collision it moves toward the character n gets destroy. do u guys think this will be expensive? tks

using UnityEngine;
using System.Collections;

public class Coins : MonoBehaviour {

    RunnerGame game;
	PlatformerCharacter2D char2D;

    void Awake()
    {
        game = GameObject.Find("Main Camera").GetComponent<RunnerGame>();
		char2D = GameObject.FindGameObjectWithTag("Player").GetComponent<PlatformerCharacter2D>();
    }
	void Update ()
	{
		if (game.CoinMagnet  !char2D.dead)
			if(Vector3.Distance(transform.position, GameObject.FindGameObjectWithTag("Player").transform.position) < 5)
				transform.position = Vector3.MoveTowards(transform.position, GameObject.FindGameObjectWithTag("Player").transform.position, Time.deltaTime *10);
	}
    void OnTriggerEnter2D(Collider2D other)
    {
        if (other.tag == "Player")
        {            
            game.Coins += 1;
            Destroy(this.gameObject);
        }
    }
}

I hope this will be helpfull

3 Likes

Physics.Overlap shere will do the job perfectly.

Also checking distance on every frame isn’t that expensive at all.

Physic engine works using trees, splitting the world into smaller chunk. So when you do any physic call, you’re not checking everything, but only stuff within specific tree nodes.

Also, I would advice using sqrMagnitude over Magnitude or Distance when doing comparison.

This is very useful

GameObject.FindGameObjectWithTag() is very slow, caching the object in a GameController singleton would be a much smarter/faster way to handle that. Also (distance1-distance2)…sqrMagnitude < distanceAway is faster than Vector3.Distance

ish…

hes only doing it once in awake… there are however other problems with that approach of course.