我希望在每个框架上移动,缩放和旋转给定的圆柱体,使其表现得像一条绳索。两点之间。
我现在有这个代码,但它并没有像预期的那样工作:
hook.transform.position = (rightHandPosition + hookDestination)/2;
hook.transform.localScale = new Vector3(0.5F, Vector3.Magnitude(hookDestination - rightHandPosition), 0.5F);
hook.transform.rotation = Quaternion.Euler(hookDestination - rightHandPosition);
你可以猜到这两点是rightHandPosition和hookDestination。现在,圆柱体随机产生了“随机”。地点,随机'旋转和巨大的尺度。
我该如何解决?
"全"脚本:
public class FirstPersonController : MonoBehaviour {
public GameObject hook;
bool isHooked = false;
Vector3 hookDestination;
Vector3 rightHandPosition;
void Start() {
hook.renderer.enabled = false;
rightHandPosition = hook.transform.position;
}
// Update is called once per frame
void Update () {
if (isHooked) {
hook.transform.position = (rightHandPosition + hookDestination)/2;
hook.transform.localScale = new Vector3(0.5F, Vector3.Magnitude(hookDestination - rightHandPosition), 0.5F);
hook.transform.rotation = Quaternion.Euler(hookDestination - rightHandPosition);
}
if (isHooked && !Input.GetMouseButton(1)) {
isHooked = false;
hook.renderer.enabled = false;
}
if (Input.GetMouseButtonDown (1) && !isHooked) {
Ray ray = GameObject.FindGameObjectWithTag ("MainCamera").camera.ViewportPointToRay (new Vector3 (0.5F, 0.5F, 0));
RaycastHit hit;
if (Physics.Raycast (ray, out hit) && hit.distance < 5000000 && hit.collider.tag != "Player") {
isHooked = true;
hookDestination = hit.point;
hook.renderer.enabled = true;
}
}
}
}
场景的截图:
答案 0 :(得分:1)
让我们假设cubeStart是起点,cubeEnd是终点。而“圆筒”就是你的圆筒,然后
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class AlignCyl : MonoBehaviour {
GameObject cubeStart;
GameObject cubeEnd;
GameObject cylinder;
Vector3 endV;
Vector3 startV;
Vector3 rotAxisV;
Vector3 dirV;
Vector3 cylDefaultOrientation = new Vector3(0,1,0);
float dist;
// Use this for initialization
void Start () {
cubeStart = GameObject.Find("CubeStart");
cubeEnd = GameObject.Find("CubeEnd");
cylinder = GameObject.Find("Cylinder");
endV = cubeEnd.transform.position;
startV = cubeStart.transform.position;
}
// Update is called once per frame
void Update () {
// Position
cylinder.transform.position = (endV + startV)/2.0F;
// Rotation
dirV = Vector3.Normalize(endV - startV);
rotAxisV = dirV + cylDefaultOrientation;
rotAxisV = Vector3.Normalize(rotAxisV);
cylinder.transform.rotation = new Quaternion(rotAxisV.x, rotAxisV.y, rotAxisV.z, 0);
// Scale
dist = Vector3.Distance(endV, startV);
cylinder.transform.localScale = new Vector3(1, dist/2, 1);
}
}
使用Unity3D 2018.1测试 我关于旋转的概念仅基于四元数。
x=rotAxis.x * sin(angle/2) = rotAxis.x;
y=rotAxis.y * sin(angle/2) = rotAxis.y;
z=rotAxis.z * sin(angle/2) = rotAxis.z;
w = cos(angle/2) = 0;
其中rotAxis是2个向量的总和,即默认的圆柱方向和所需的方向。角度为180度,因为我们希望圆柱绕rotAxis旋转180度。它是四元数旋转的定义(围绕轴旋转)。
答案 1 :(得分:0)
fafase的评论是正确答案:使用LineRenderer
。
hookRender.SetPosition(0, rightHandPosition);
hookRender.SetPosition(1, hookDestination);