Stick objects to player on contact

Hey there,

first: I’m a german graphic design student, and I’m working on my first game. So scripting is relative new to me.

The plan where I need some help: the are small cubes lying on the floor. When the player walks through the cubes, they stick to the player-model. Like if they were magnetic or burdocks.

Thanks for your help
Brian

Hej there. That should be easy.

  1. Make sure your player has a Character Controller or Rigidbody component in the scene.

  2. Add any form of collider to the boxes you want to stick to the player

  3. Add a (for example) C# script to the player which includes (besides start und update) this method:

    private void OnCollisionEnter(Collision c){
    	c.transform.parent = gameObject.transform;
    }
    

that makes the cube a child object of the parent (the player) thus it moves with the player.

I hope I understand your probleme correctly and you have an idea what to do.

Make the cubes to face the player (or a point in the player body) using transform.LookAt() and, after, transform.Translate(Vector3.forward * Time.deltaTime). Only activates this (the magnetism) when the player is near, check using Vector3.Distance().

When the player is too near I suggest you to make the object stop moving and make it a parent of the player (Something like transform.parent = player.transform).