[英]Unity 3D - Object position and its size
我的Unity3D项目存在以下问题。 我将尝试在图像上进行描述。
因此,我想将对象合并为1。当对象1和2碰撞时,它们将合并(对象2成为对象1的子对象)。 在实践中,当对象1中的螺栓(这个蓝色的“东西”是螺栓)与对象2碰撞时,它们应该合并。 我想将对象2放置在对象1的顶部(说顶部,我的意思是红线在哪里,第二张图片中的右图)。 因此,我决定将第二个对象的localPosition设置为与bolt的localPosition相等(螺栓也是对象1的子对象)。 但这是错误的(第二张图片,左侧)。 所以我知道我应该将第二个对象的高度的一半加到他的一个轴上。 但它仍然不是完美的。 而且我也不知道应该将其添加到哪个轴。 当我增加一半的高度时,我应该使用localPosition还是正常位置?
我的代码:
void OnTriggerEnter(Collider c) {
if(transform.IsChildOf(mainObject.transform)) {
childObject.transform.SetParent (mainObject.transform);
childObject.transform.localPosition = boltObject.transform.localPosition;
childObject.transform.position = new Vector3 (childObject.transform.position.x, childObject.transform.position.y, (float)(childObject.transform.position.z + childObject.GetComponent<Renderer>().bounds.size.z));
}
}
我必须补充一点,对象可以具有不同的大小,所以我不能只添加数字,它必须灵活。 我将非常感谢您的帮助。
编辑:这是我的整个代码:
using UnityEngine;
using System.Collections;
public class MergeWithAnother : MonoBehaviour {
public GameObject mainObject;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
void OnTriggerEnter(Collider c) {
if(transform.IsChildOf(mainObject.transform)) {
if (c.gameObject.name == "holeForBolt" && c.gameObject.transform.parent.gameObject != mainObject) {
Destroy (c.gameObject.transform.parent.gameObject.GetComponent("MouseDrag"));
Destroy (c.gameObject.transform.parent.gameObject.GetComponent("RotateObject"));
c.gameObject.transform.parent.gameObject.transform.SetParent (mainObject.transform);
c.gameObject.transform.parent.gameObject.transform.localPosition = gameObject.transform.localPosition;
c.gameObject.transform.parent.gameObject.transform.position = new Vector3 (c.gameObject.transform.parent.gameObject.transform.position.x, c.gameObject.transform.parent.gameObject.transform.position.y, (float)(c.gameObject.transform.parent.gameObject.transform.position.z + c.gameObject.transform.parent.gameObject.GetComponent<Renderer>().bounds.size.z));
c.gameObject.transform.parent.gameObject.transform.localRotation = gameObject.transform.localRotation;
c.gameObject.transform.parent.gameObject.transform.localRotation = new Quaternion (360 + c.gameObject.transform.parent.gameObject.transform.localRotation.x, c.gameObject.transform.parent.gameObject.transform.localRotation.y, c.gameObject.transform.parent.gameObject.transform.localRotation.z, c.gameObject.transform.parent.gameObject.transform.localRotation.w);
Destroy (c.gameObject.transform.parent.gameObject.GetComponent<CapsuleCollider>());
Destroy (gameObject);
Destroy (c.gameObject);
CapsuleCollider cc = mainObject.GetComponent<CapsuleCollider>();
cc.height *= 2;
cc.center = new Vector3(0, 0, 1);
}
}
}}
我将解释这意味着什么:
只需使用第一个对象的位置和bounds.size:
vector3 posOfSecObject =新的vector3(0,0,0);
posOfSecObject.y + = FIRSTOBJECT.GetComponent()。Renderer.bounds.size.y;
我使用了Y轴,我不知道您需要哪一个,请尝试;)我使用此代码来建造一栋由地板组成的房屋
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.