unity3d - 夹在两个物体之间
问题描述
我需要两个物体之间的抓地力,实际上小立方体是一个具有刚体的玩家,而大立方体是一个可以帮助小立方体跳上它并继续跳到其他大立方体上以到达目的地的物体。我需要当玩家跳跃并降落在旋转的立方体上时,它们之间应该有摩擦,默认情况下玩家应该用大立方体旋转,因为它在大立方体上。
预期的结果是具有刚体的小立方体也应该随着大立方体旋转,因为大立方体正在旋转并且在大立方体上:
解决方案
您可以将小立方体游戏对象设置为大立方体游戏对象的子对象。这应该是诀窍。
----评论后编辑
如果您需要更改子层级(因为小立方体可以移开),那么您需要一个脚本来在需要时添加和删除子级。
=> 当玩家(小立方体)在大立方体上时,你就是大立方体的孩子。
=> 当玩家(小方块)离开大方块时,你就可以将玩家移到大方块。
如果您使用刚体,则可以使用OnCollisionEnter和OnCollisionExit。
您可以将此单一行为附加到大立方体上。
public class BigCubeScript : MonoBehaviour
{
private void OnCollisionEnter(Collision other)
{
//check if the colliding object is player (here I'm using a tag, but you may check it as you prefer)
if (other.gameObject.tag == "Player")
//change the parent of the player, setting it as this cube
other.transform.SetParent(this.transform);
}
void OnCollisionExit(Collision other)
{
if (other.gameObject.tag == "Player")
//remove the player from the cube
other.transform.SetParent(null);
}
}
您还可以对玩家的旋转施加力,直到他停留在立方体上。在这种情况下,很好地平衡旋转力非常重要(您可以在编辑器中尝试)。
public class BigCubeScript : MonoBehaviour
{
//you may change this to add or remove the force
Vector3 _rotationForce = new Vector3(0, 5, 0);
private void OnCollisionStay(Collision other)
{
var rigidbody = other.gameObject.GetComponent<Rigidbody>();
Quaternion deltaRotation = Quaternion.Euler(_rotationForce * Time.deltaTime);
rigidbody.MoveRotation(rigidbody.rotation * deltaRotation);
}
}
本Unity 教程中 OnCollisioEnter 和 OnCollisionExit 的更多信息
本Unity 教程中标签的更多信息
推荐阅读
- python - 如何从分割掩码中找到 IoU?
- woocommerce - 在 Woocommerce 结帐中动态更新费用
- python - Python:仅保留最后 n 个插入键的字典
- javascript - 如何从 React 发送表单数据以表达
- python - 在 ubuntu 16.04 上使用 nginx 和 uwsgi 部署 django 项目时,nginx 无法正确提供文件
- java - 为什么 @Required 被 Spring 忽略?
- python - 使用列表理解修改字典列表
- c# - 从 Windows 窗体将值插入 SQL 数据库时出现不正确的语法错误
- wordpress - 如何将隐私政策页面与接受复选框上的标签文本链接?
- reactjs - 使用 AWS Cognito 对用户进行身份验证时出现网络错误