C# 相对连接锚的弹簧接头
我想为弹球桌做一个柱塞。它基本上是一个带有刚体和弹簧关节的立方体。当按下一个特定的键时,我试图向弹簧的connectedAnchor添加一些z值以移动立方体,当不再按下该键时,connectedAnchor将返回其原始位置 问题是,connectedAnchor操作发生在worldspace中,由于我的表是旋转的,因此沿z轴移动立方体是不正确的。本质上,我要寻找的是一种影响连接锚的方法,但是使用立方体变换的局部轴,而不是世界空间轴 要获得原始的connectedAnchor,我选中“自动配置”,然后在进行操作之前取消选中它。联合公司的文件说这应该行得通,但实际上不行C# 相对连接锚的弹簧接头,c#,unity3d,C#,Unity3d,我想为弹球桌做一个柱塞。它基本上是一个带有刚体和弹簧关节的立方体。当按下一个特定的键时,我试图向弹簧的connectedAnchor添加一些z值以移动立方体,当不再按下该键时,connectedAnchor将返回其原始位置 问题是,connectedAnchor操作发生在worldspace中,由于我的表是旋转的,因此沿z轴移动立方体是不正确的。本质上,我要寻找的是一种影响连接锚的方法,但是使用立方体变换的局部轴,而不是世界空间轴 要获得原始的connectedAnchor,我选中“自动配置”,
Here's my script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlungerController : MonoBehaviour {
public float movement_increment_z;
public float max_movement_z;
private SpringJoint spring;
private Vector3 orig_anchor;
private void Start() {
spring = GetComponent<SpringJoint>();
if (!spring) { throw new System.Exception("spring joint is needed"); };
orig_anchor = spring.connectedAnchor;
}
public void processPlungerInput (bool isKeyPressed) {
Debug.Log(orig_anchor);
if (isKeyPressed) {
if (spring.connectedAnchor.z < max_movement_z) {
spring.connectedAnchor += new Vector3(0,0,movement_increment_z);
} else {
spring.connectedAnchor = orig_anchor;
}
}
}
}
刚体约束在除z轴移动以外的所有对象上 我最终采取了一种稍微不同的方法。我没有改变弹簧的连接锚定,而是保持不变,并将连接体设置为静态定位的原点变换 按下该键时,我临时将弹簧设置为0,然后更改柱塞对象的位置。当按键未按下时,我将弹簧设置为一个高值,使其回扣到锚定点 为了解决约束问题,我没有使用刚体检查器上的选项(仅锁定世界空间轴上的位置),而是使用脚本将旋转和x/y位置设置为每帧的原始值 现在,脚本如下所示:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlungerController : MonoBehaviour {
public float movement_increment_z;
public float max_movement_z;
public float spring_power;
private SpringJoint spring;
private Vector3 orig_anchor;
private Quaternion orig_rotation;
private float orig_pos_x, orig_pos_y;
private void Start() {
spring = GetComponent<SpringJoint>();
if (!spring) { throw new System.Exception("spring joint is needed"); };
orig_anchor = spring.connectedAnchor;
orig_rotation = transform.localRotation;
orig_pos_y = transform.localPosition.y;
orig_pos_x = transform.localPosition.x;
}
public void processPlungerInput (bool isKeyPressed) {
if (isKeyPressed) {
spring.spring = 0;
if (transform.localPosition.z < max_movement_z) {
transform.localPosition += new Vector3(0,0,movement_increment_z);
}
} else {
spring.spring = spring_power;
}
}
// preserve only z axis movement and no rotation at all.
private void FixedUpdate() {
transform.localRotation = orig_rotation;
transform.localPosition = new Vector3(orig_pos_x, orig_pos_y, transform.localPosition.z);
}
}