SamSic
SamSic

Reputation: 357

Place objects based on coordinates, not on the central coordinates in Unity

enter image description here I'm creating mesh objects dynamically based on the screen.

So objects that contain mesh objects are always the same size, but mesh objects have different shapes and sizes.

I want you to see my picture and understand it. In fact, blue area is transparent.

I am currently using a mobile camera to shoot Ray at the floor, and I want to place the object at the point where the Ray has hitted.

enter image description here But this seems to require a lot of calculations.

I think we should use other coordinates than the object's central coordinates first. And I think we should place the object a little bit above the collision point. Half the size of the mesh object,

So I tried this, but I failed. How can I solve this?

Below is my source code.

Vector3 hitPositon = hit.Pose.position;

Vector3 meshObjectCenter = ObjectPrefab.GetComponent<Renderer>().bounds.center;
Vector3 meshObjectSize = ObjectPrefab.GetComponent<Renderer>().bounds.size;

Vector3 CenterPointRevision = meshObjectCenter - hitPositon;
Vector3 YAxisRevision = new Vector3(0, meshObjectSize.y / 2, 0);
           
Vector3 NewPoint = ARObjectPrefab.transform.position - CenterPointRevision + YAxisRevision;
           
ObjectPrefab.transform.position = NewPoint;

enter image description here

Object is in this format, and the picture above looks successful but fail case.

Upvotes: 0

Views: 253

Answers (1)

Colin Young
Colin Young

Reputation: 3058

The position is just the hit location minus the offset to center plus the y-axis offset:

Vector3 hitPositon = hit.Pose.position;
Vector3 meshObjectCenter = ObjectPrefab.GetComponent<Renderer>().bounds.center;
Vector3 meshObjectSize = ObjectPrefab.GetComponent<Renderer>().bounds.size;
Vector3 YAxisRevision = new Vector3(0, meshObjectSize.y / 2, 0);
ObjectPrefab.transform.position = hitPositon - meshObjectCenter + YAxisRevision;

Upvotes: 1

Related Questions