使用C#在Unity3D中获取要摆动的对象
本文关键字:对象 获取 Unity3D 使用 | 更新日期: 2023-09-27 18:27:30
我正试图在Unity3D中模拟一艘船。我需要它能做的是像真正的船一样在水中摇晃,只要它碰到什么东西。我已经让船相撞了,所有的轴都解锁了。然而,这意味着船会旋转,然后继续以一个奇怪的角度行驶(比如面向天空)。
有没有一种方法可以让船尝试恢复到原来的旋转,而不是突然恢复到准确的值,而是简单地来回"摇晃",然后减速,最终再次停止在正确的旋转?
以下是我尝试使用的代码:
void FixedUpdate ()
{
wobble();
}
void wobble()
{
if (this.transform.eulerAngles.x < 270)
{
this.rigidbody.AddTorque((float)19, (float)0, (float)0, ForceMode.Force);
}
else if (this.transform.eulerAngles.x > 270)
{
this.rigidbody.AddTorque((float)-19, (float)0, (float)0, ForceMode.Force);
}
else{}
if (this.transform.eulerAngles.z < 0)
{
this.rigidbody.AddTorque((float)19, (float)0, (float)0, ForceMode.Force);
}
else if (this.transform.eulerAngles.z > 0)
{
this.rigidbody.AddTorque((float)-19, (float)0, (float)0, ForceMode.Force);
}
else{}
}
然而,现在当我的物体碰到什么东西时,它就开始失控旋转。有什么想法吗?
您可以使用tweening。在两个值之间平滑地更改值是一种绝妙的技术。在这种情况下,你可以从你笨拙的弹跳角度到你的船坐着旋转,在两者之间用粗花呢。有一些很好的插件可以使用,比如iTween,这非常棒,但我将向您展示一些半伪半超级谷物代码,让您开始了解"旋转校正"的概念
比方说,我的船撞上了一个漂亮的大浪,它把我的船指向20度角。
我在X上的欧拉角是20,我可以通过以恒定的速率增加值来将其返回到0。我只是在这里显示X,但你可以对Z轴重复这个过程。我会排除Y,因为你会在Y上使用你的船的方向,你不想搞砸你的船导航。
Update()
float angleDelta;
// check if value not 0 and tease the rotation towards it using angleDelta
if(transform.rotation.X > 0 ){
angleDelta = -0.2f;
} elseif (transform.rotation.X < 0){
angleDelta = 0.2f;
}
transform.rotation.X += angleDelta;
}
这个极其简单的实现完成了任务,但却有着令人难以置信的"敏捷"answers"紧张"的好处。因此,我们想添加一些平滑处理,使其成为一艘更加逼真的船。
我们通过在angleDelta中添加一个变量来实现这一点:
Vector3 previousAngle;
float accelerationBuffer = 0.3f;
float decelerationBuffer = 0.1f;
Update()
Vector3 angleDelta;
//assuming that x=0 is our resting rotation
if(previousAngle.X > transform.rotation.X && transform.rotation.X > 0){
//speed up rotation correction - like gravity acting on boat
angleDelta.X += (previousAngle.X - transform.rotation.X) * accelerationBuffer;
} elseif(previousAngle.X < transform.rotation.X && transform.rotation.X > 0
//angle returning to resting place: slow down the rotation due to water resistatnce
angleDelta.X -= (previousAngle.X - transform.rotation.X) * deccelerationBuffer;
}
//If boat pointing to sky - reduce X
if(transform.rotation.X > 0 ){
transform.rotation.X -= angleDelta.X * Time.deltaTime;
//If boat diving into ocean - increase X
} elseif (transform.rotation.X < 0){
transform.rotation.X += angleDelta.X * Time.deltaTime; //Must not forget to use deltaTime!
}
//record rotation for next update
previousAngle = transform.rotation;
}
这是一个非常粗略的草案,但它跨越了我试图解释的理论-你需要相应地调整你自己的代码,因为你还没有包含任何你自己的(给我们粘贴一个片段,也许我们可以详细说明!)