Coin and Life magnet - What's wrong with my code?
hi, i'm working on a platformer game, and there is some extra life and coins on some of my platforms. i want to use a magnet which if it turns on, all coins and lives start moving through the player (the coin and life trigger functions have been already written). so i created an empty gameobject child for my player and i attached a giant circle collider2d to it. i also attached this code:
void OnTriggerEnter2D (Collider2D target){
if (target.tag == "Coin" || target.tag == "Life") {
target.transform.position = Vector3.MoveTowards (target.transform.position, myMoon.transform.position, 5f*Time.deltaTime);
}
but it is not working. if use 5f instead of 5f*Time.deltaTime it will work, but without any smooth or animated coin/life movement. what should i do? shall i use Vector3.Lerp?? Thank you
Answer by jgodfrey · Jun 25, 2016 at 01:38 PM
That's because OnTriggerEnter2D only fires once, when an object enters the trigger. So, your MoveTowards method is only called once, which isn't what you want. Instead, in your OnTriggerEnter2D method, you'll want to set a boolean flag when you detect that you've collided with a Coin or Life object. Then, do your MoveTowards code in Update if that flag is set.
That way, the MoveTowards code will fire in each frame as long as the flag is set. Once the object you're moving is "close enough" to its destination, you'd want to unset your boolean flag...
Additionally, you might want to look at the PointEffector2D class as it's designed to do exactly this...
Your answer
![](https://koobas.hobune.stream/wayback/20220612083633im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Moving an object to a random position between two objects 1 Answer
How can change camera local position smoothly between 3 point 0 Answers
Vector3.Lerp not moving object backwards 0 Answers
How to use Vector3.Lerp in combination with OncollisionEnter and update 1 Answer
sometimes Polygon collider do not work properly and no collision happens 0 Answers