我有这个代码让一个物体在Y轴上旋转。但我想只在Z轴上旋转对象。我试图更改 hPlane 值,但没有运气。 我怎样才能做到这一点? 感谢
private Ray ray;
private Quaternion target;
private float speed = 1000.0f;
// Update is called once per frame
void Update () {
if (Input.GetMouseButton (0)) {
ray = Camera.main.ScreenPointToRay (Input.mousePosition);
Plane hPlane = new Plane(Vector3.up, Vector3.zero);
float distance = 0;
if(hPlane.Raycast(ray, out distance)){
Vector3 targetPoint = ray.GetPoint(distance);
targetPoint += transform.position;
Quaternion targetRotation = Quaternion.LookRotation(targetPoint - transform.position);
float step = speed * Time.deltaTime;
transform.rotation = Quaternion.RotateTowards(transform.rotation, targetRotation,step);
}
}
}
更新
我的目标是使用鼠标点击在Z轴上平滑旋转条形(立方体网格)。只有在(这部分我无法做到)鼠标触摸条的角落时才会发生旋转。
我已经使用此代码完成了Z轴旋转,但旋转非常低(即使速度= 1000.0f),我想它顺时针旋转。但是我想要向两个方向移动横杆,并且像Quaternion.RotateTowards那样,动作会更加平滑和快速。
由于
private Ray ray;
private RaycastHit hit;
private Quaternion target;
private float speed = 1000.0f;
// Update is called once per frame
void Update () {
if (Input.GetMouseButton (0)) {
ray = Camera.main.ScreenPointToRay (Input.mousePosition);
if(Physics.Raycast(ray, out hit)){
//transform.position = new Vector3(hit.point.x, hit.point.y, 0);
target = Quaternion.Euler(0.0f,0.0f, hit.point.z * speed);
transform.rotation = Quaternion.Slerp(transform.rotation, target, Time.deltaTime);
}
}
}
答案 0 :(得分:0)
我建议你改变物体轴的方向。为了更好地使用四元数函数,编辑条形图以使局部Y具有旋转轴和局部Z作为外观方向。
然后使用此代码:
if (Input.GetMouseButton(0))
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit))
{
Vector3 distance = hit.point - transform.position;
distance.y = 0;
Quaternion targetRotation = Quaternion.LookRotation(distance);
transform.rotation = Quaternion.RotateTowards(transform.rotation, targetRotation, Time.deltaTime * speed);
}
}
您的栏只会围绕Y轴旋转。