I'm trying to make a magnet PowerUp in Unity. I used this script, which I attached to the coin GameObject:
public GameObject attractedTo;
private float strengthOfAttraction = 3f;
void FixedUpdate ()
{
Vector3 direction = attractedTo.transform.position - transform.position;
gameObject.GetComponent<Rigidbody>().AddForce (strengthOfAttraction * direction);
}
I have two problems : 1. Only newly spawn coins are attracted to the player 2. For some reason, the coins move only in straight lines, so most of them goes past the player
Anyone knows how this can be fixed? Any help will be appreciated!
Major issue on your code. You have to recreate your procedure logic on how you make the coins get closer to the Player.
First Major problem is this.
void FixedUpdate()
So on a fix amount of time per frame. You are trying to Declare a Variable Vector3 : Vector3 direction = attractedTo.transform.position - transform.position;
So frame will recalculate and create a new pointer name direction
then you try to find gameObject.GetComponent<Rigidbody>().AddForce (strengthOfAttraction * direction);
your Own Component in your gameObject. Then Call Addforce. AddForce. And you didn't even use time.deltatime.
Addforce Will push the rigidbody depending on the direction you input. So it will go straight. And you are doing this Every Fix amount of frame per sec.
First fix your procedure. My recommendation is this.
Use the Smooth Follow script. Made by Unity3D get your Reference there. It is also installed already in the script section in your Editor. If you are having problem finding it, go to this link and check he script.
[ Update Answer ]
For the 2nd Problem that only new coins is getting attracted.
Check all of this situations.
attractedTo
variable is blank. attractedTo
when Player Spawned. You can either Achieve that on Instantiate then find all GameObjects with TAG. Then getcomponent then assign attractedTo
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.