- Home /
Positioning gameobject on collider bounds.
Hello. I am trying to position gameobject A on the perimeter of gameobject B's collider. I am using Bounds.ClosestPoint to get the closest point to gameobject B's collider but the issue is I only want to get points that are on the perimeter of the collider not inside of the collider. Could anyone guide me in the right direction to achieve this? Thank you.
Answer by FeedMyKids1 · Jul 06, 2020 at 10:29 AM
In testing this I made a sphere collider with a script on it and then a sphere object that's smaller than the collider to visualize where the first collider is.
When anything collides with the collider, the red gameobject of choice will appear at the point of contact using this script:
public class ColliderTest : MonoBehaviour
{
[SerializeField] private GameObject showPointPrefab = null;
private void OnCollisionEnter(Collision collision)
{
Vector3 point = collision.contacts[0].point;
Instantiate(showPointPrefab, point, Quaternion.identity);
}
}
To better answer the question:
In the Collision class, you get some nifty information like the 'contacts' array which holds information about each point of contact in the collision but that first point (accessed with the 'point' property) is where the collision occurred.
In your case, you can say GameObjectB.transform.position = collision.contacts[0].point;
And if you want the object to be on the outside of the collider, you can use the contact.normal to offset it.
Thank you very much! I managed to get it working with your approach after some slight modifications :)
Your answer
Follow this Question
Related Questions
Bounds is 0 when Instantiated 2 Answers
Converting Collider to Bounds variable? 1 Answer
My object is going through boundaries Problem! 1 Answer
How does Unity's Collider.Bounds work? 0 Answers