public Rigidbody projectile;
public Transform startBulletPosition;
public float speed;
public float rotationSpeed;
public Camera camera;
Vector3 startingDirection;
void Start() {
startingDirection = startBulletPosition.transform.forward;
}
void Update() {
if (Input.GetButtonDown("Fire1")) {
RaycastHit hit;
Vector3 targetDirection;
if (Physics.Raycast(Camera.main.transform.position, camera.transform.forward, out hit)){
targetDirection = hit.transform.position - startBulletPosition.position;
} else {
targetDirection = startingDirection;
}
Vector3 newDirection = Vector3.RotateTowards(startBulletPosition.transform.forward, targetDirection, rotationSpeed * Time.deltaTime, 0.0f);
startBulletPosition.transform.forward = newDirection;
Rigidbody clone;
clone = Instantiate(projectile, startBulletPosition.position, startBulletPosition.rotation) as Rigidbody;
clone.velocity = targetDirection * speed;
}
}
我就从摄像机位置做一个光线投射,看看有什么你可以打,然后旋转武器这个方向努力。正如我的示例代码。武器将指向您的相机Raycast命中的中心视图。
您也可以通过该公共浮动控制最大转动速度。这将会带来不错的武器运动,而不仅仅是瞬间跳跃。
下面是我在这个片段中使用的实况链接: https://docs.unity3d.com/ScriptReference/RaycastHit.html
如果光线投射命中,武器的储存原来的方向将被使用。 (假设startBulletPosition是武器的变换......)
如果需要,您可以将maxDistance参数添加到Physics.Raycast调用中,以限制此行为处于活动状态的距离。
因为你不是在中心生成子弹,所以你可以尝试** Raycast **来查看是否有任何物体在你的面前。如果是这样,请获取** BulletSpawn **点和**前面**对象之间的距离。计算子弹击中中心的角度。在你的**变形中使用它** – Thalthanas
你之前是否已经去过实际的拍摄范围?如果我不得不像这样拿着我的枪(或者如果它被安装在某种东西上),我完全期待这种行为。 – Fildor