Eduardo Corona
Eduardo Corona

Reputation: 1332

How to place a Mesh/gameObject in the middle of the camera's FoV when the origin is not on the mesh?

I'm making a Unity Game where I need to display 3D models that are downloaded from a server in the center of the camera FoV, the problem is that some of the models don't have the pivot on the mesh, so my code does not work very well for that scenarios:

    Vector3 positionInFront =  CameraCache.Main.transform.position + (CameraCache.Main.transform.forward * 1); 
    transform.position = positionInFront ;   

Any idea of how can I solve this issue without the use of parents/changing the hierarchy? This cose solve my problem but when the model is big in terms of polycount the app struggles to perform changes on the hierarchy:

    GameObject aux = new GameObject();
    aux.transform.position = targetCenter;
    transform.SetParent(aux.transform);
    aux.transform.position = positionInFront;
    transform.transform.SetParent(null);
    GameObject.Destroy(aux);

Upvotes: 0

Views: 559

Answers (1)

derHugo
derHugo

Reputation: 90724

You can use the center of geometry by using e.g. Renderer.bounds.center in order to calculate the needed delta vector to move the object in such way that the center ends up in the target position like e.g.

// Model pivot in worldspace
var position = yourModel.position;
// Center if geometry in worldspace
var center = yourModel.GetComponent<Renderer>().bounds.center;
// vector from center to pivot
var centerToPositionDelta = position - center;
// Your target position in worldspace
var positionInFront =  CameraCache.Main.transform.position + CameraCache.Main.transform.forward * 1; 
// By adding the shifting vector center -> position
// you move the object just so the center ends up in the targetPosition
transform.position = positionInFront  + centerToPositionDelta;   

Typed on smartphone but I hope the idea gets clear

Upvotes: 2

Related Questions