- Home /
Follow me magnet effect
Wondering if someone could give me some pointers in my script that uses a magnet effect to make a cube (with rigidbody) follow a cylinder / magnet (kinematic rigidbody) using AddForce.
The functions make the Cube follow and face the cylinder / magnet. They both work well, but what I really want is for the Cube to snap to the bottom of the cylinder. Not hover underneath it. (see pics). If anyone could suggest what I need to add to the code to achieve this I'd super grateful.
It almost seems as if the transform point for the cylinder is underneath it (but it isn't its a standard unity Game Object with a central origin point.
Script attached to cube
public class CubeMove : MonoBehaviour {
private Rigidbody CubeRigidBody;
public GameObject Magnet;
// Start
void Start () {
CubeRigidBody = this.GetComponent<Rigidbody> ();
}
// Update
void Update () {
FollowMagnet ();
FaceMagnet ();
}
// cube follow the magnet
void FollowMagnet () {
// cube follows magnet
float strength = 100f; // magnet strength
Vector3 DirectionToMagnet = (Magnet.transform.position - transform.position).normalized;
CubeRigidBody.AddForce (DirectionToMagnet * strength, ForceMode.Force);
}
// face the magnet
void FaceMagnet () {
Vector3 DirectionToMagnet = (Magnet.transform.position - this.transform.position).normalized;
this.transform.forward = DirectionToMagnet;
}
}
Start
Play: magnet / cylinder force takes effect Cube moves toward cylinder and hover underneath
Answer by r-dickinson · Sep 11, 2020 at 10:01 PM
I figured this out in case anyone stumbles across this question. The cylinder / magnet has a capsule collider that reaches below the mesh object. The cube can only move to the edge of the collider, hence it never touches the cylinder.
The solution: use a flat bottomed box collider on the cylinder.
Your answer
Follow this Question
Related Questions
Game Objects acting like magnets? 1 Answer
How to release an object from a magnet through a press of a button 1 Answer
AI to follow player not working 3 Answers
Follow AI Script , AI gets launched 1 Answer
Follow and Levitation around a object 0 Answers