c# - 通过 GetComponentInChildren 访问 Unity3D 可配置关节组件
问题描述
我有一个胶囊和一个由可配置关节连接的球体。我使用胶囊刚体移动玩家,球体充当脚轮(就像带悬架的独轮车)。
由于球体是胶囊的孩子,我正在使用 GetComponentInChildren 尝试访问可配置关节、Y 驱动器、位置弹簧(浮点值)。
我迷路了试图用谷歌搜索这个问题。
这是相关代码,里面的一切都//Comment
不起作用:
public class PlayerMovement : MonoBehaviour
{
private Rigidbody rb;
public float moveSpeed = 10f;
public float distanceGround;
public bool isGrounded = false;
public bool isCrouch = false;
void Awake()
{
rb = GetComponent<Rigidbody>();
}
void Start()
{
distanceGround = GetComponent<Collider>().bounds.extents.y;
}
void FixedUpdate()
{
Movement();
}
private void Movement()
{
float inputX = Input.GetAxis("LStickHorz");
float InputZ = -Input.GetAxis("LStickVert");
float multiplier = 1f;
if (!Physics.Raycast (transform.position, -Vector3.up, distanceGround + 1.5f))
{
isGrounded = false;
print("IN AIR.....");
}
else
{
isGrounded = true;
print("....onGround");
//Debug.DrawRay(?,?, Color.red, 1.25f);
}
if (Physics.Raycast (transform.position, -Vector3.up, distanceGround + .2f))
{
isCrouch = true;
print("VVVVVVVVVVVVVV");
//ConfigurableJoint cj = gameObject.GetComponentInChildren(typeof(ConfigurableJoint)) as ConfigurableJoint;
//set y spring value
//cj.yDrive.positionSpring = 50f;
}
else
{
isCrouch = false;
}
if (!isGrounded)
{
multiplier = .2f;
}
if (isCrouch)
{
multiplier = .2f;
}
Vector3 moveVector = new Vector3(inputX * multiplier, 0.0f, InputZ * multiplier);
//if ()
rb.AddForce(moveVector * moveSpeed);
}
}
解决方案
让我们从您的第一条评论开始,即 function Debug.DrawRay()
。如果您查看此处的文档,它将告诉您函数的所有参数并向您展示一个示例。对于这个函数,前两个参数是位置和方向:
Debug.DrawRay(transform.position, Vector3.up * 5, Color.red, 1.25f)
第二个问题是您不能positionSpring
直接设置字段。您需要yDrive
在另一个变量中存储对 的引用,更改 的值positionSpring
,然后设置yDrive
为 temp 变量:
// Get the COnfigurableJoint component
ConfigurableJoint cj = gameObject.GetComponent<ConfigurableJoint>();
// Grab a reference to the JointDrive
JointDrive jd = cj.yDrive;
// Set the value of positionSpring here
jd.positionSpring = 50.0f;
// Apply the changes you made to the yDrive back to the ConfigurableJoint
cj.yDrive = jd;
推荐阅读
- arrays - 如何生成只显示一次的随机数?
- python - 如何使用 Selenium Python 提取 href?
- google-apps-script - 如果已存在同名文件,请勿保存 PDF(Google App Script + Google Sheets)
- c - 我可以使用什么来进行输入转换而不是 scanf?
- python - 如何以更快的方式制作包含列表的字典
- r - R read.csv colClasses scan() 预期'逻辑',得到'“FALSE”'
- vba - 如何修复此代码以防止访问崩溃。我假设循环出现了一些错误
- javascript - 如何阻止某人将井字棋放在同一个地方
- javascript - HTML:如何使点击监听器忽略放置在图标上的不可见按钮
- apache-kafka - 使用 Confluent Cloud 和 Snowflake Kafka 连接器时,SF_KAFKA_CONNECTOR 名称为空或无效错误