我与我的物体在统一2d中有一个问题,当我将指向框碰撞器的箭头射向另一个元素时,当它撞上并进入子级时,我的意思是箭头成为父级(BOX)的子级向左和向右旋转..我真的想禁用孩子的向左和向右旋转..框(父级)仍然需要像以前一样旋转。.我有这样的代码,并且我的箭头在刚体2d处于运动模式...
这是箭头的脚本..
{
public float flySpeed = 20f;
private Rigidbody2D arrowBody;
private bool shouldFly;
// Start is called before the first frame update
void Start()
{
shouldFly = true;
arrowBody = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update()
{
if (shouldFly == true)
{
//make our pin fly
arrowBody.MovePosition(arrowBody.position + Vector2.up * flySpeed * Time.deltaTime);
}
}
private void OnTriggerEnter2D(Collider2D collision)
{
if(collision.tag == "target")
{
shouldFly = false;
transform.SetParent(collision.gameObject.transform);
} else if(collision.tag == "arrow")
{
SceneManager.LoadScene("quickGameOverScene");
}
}
}
答案 0 :(得分:0)
我真的很困惑您要做什么。我不知道您是否要冻结旋转或移动,所以我将同时发布这两个答案。为了防止由父对象引起的平移和旋转,您可以像这样使用LateUpdate
:
Quaternion InitRot;
Vector3 InitPos;
void Start () {
InitRot = transform.rotation;
InitPos = transform.position;
}
void Update()
{
//figuring out when to save position when attached to BOX
if(gameObject.transform.parent == null)
{
InitRot = transform.rotation;
InitPos = transform.position;
}
}
void LateUpdate () {
//If attached to box do not translate do not rotate
if (gameObject.transform.parent != null)
{
transform.rotation = InitRot;
transform.position = InitPos;
}
}
您可以从here
了解有关此解决方案的更多信息编辑 由于上述答案不适用于OP。我弄清楚了实际的问题是什么。 OP的代码非常适合移动箭头,但问题最可能出在他旋转盒子的地方。
如果他使用transform.Rotate(Vector3.forward* 90)
旋转盒子,由于每个Update
中的帧时间都不相同,因此每个Update
中相同的旋转量会导致变形。因此,他需要使用Time.deltaTime
旋转盒子以实现一致的旋转,如下所示:transform.Rotate(Vector3.forward* 90*Time.deltaTime);
这样可以在每个时间间隔内旋转盒子相同的量并消除变形。这些是我用于该任务的脚本,它对我有用。
箭头脚本:
public float flySpeed = 20f;
private Rigidbody2D arrowBody;
private bool shouldFly;
private Vector2 initPos;
private Quaternion initRot;
// Start is called before the first frame update
void Start()
{
shouldFly = true;
arrowBody = GetComponent<Rigidbody2D>();
//arrowBody.isKinematic = true;
initPos = gameObject.transform.position;
initRot = gameObject.transform.rotation;
}
// Update is called once per frame
void Update()
{
if (shouldFly == true)
{
//make our pin fly
arrowBody.MovePosition(arrowBody.position + Vector2.up * flySpeed * Time.deltaTime);
}
if(gameObject.transform.parent == null)
{
initPos = gameObject.transform.position;
initRot = gameObject.transform.rotation;
}
}
void LateUpdate()
{
if (gameObject.transform.parent != null)
{
gameObject.transform.position = initPos;
gameObject.transform.rotation = initRot;
}
}
private void OnTriggerEnter2D(Collider2D collision)
{
Debug.Log("Collision happened");
if (collision.tag == "target")
{
shouldFly = false;
transform.SetParent(collision.gameObject.transform);
}
else if (collision.tag == "arrow")
{
SceneManager.LoadScene("quickGameOverScene");
}
}
以及用于旋转框的脚本:
public float rotationSpeed = 70f;
void Update()
{
transform.Rotate(Vector3.back, rotationSpeed * Time.deltaTime);
}