Unity 3D如何将武器瞄准光线投射

Unity 3D how to aim a weapon to a raycast hit

我有一个发射射弹的武器,我试图将武器旋转到光线投射命中。我也附上了两个脚本我的武器一个用于射击,一个用于瞄准射击脚本工作正常。 这是我的武器脚本,它启动了我的射弹:

using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Security.Cryptography;
using System.Threading;
using UnityEngine;
using UnityEngine.AI;
using Random = UnityEngine.Random; //   |source: https://community.gamedev.tv/t/solved-random-is-an-ambiguous-reference/7440/9

public class weapon_shooting : MonoBehaviour
{
    //deklariere projektil |source: https://docs.unity3d.com/ScriptReference/Object.Instantiate.html
    public GameObject projectilePrefab;
    private float projectileSize = 0;
    public Rigidbody rb;
    public float projectileSpeed = 50;
    public float projectileSizeRandomMin = 10;
    public float projectileSizeRandomMax = 35;

    void Update()
    {
        // Ctrl was pressed, launch a projectile
        if (Input.GetButtonDown("Fire1"))
        {
            //random sized bullets
            projectileSize = Random.Range(projectileSizeRandomMin, projectileSizeRandomMax);
            projectilePrefab.transform.localScale = new Vector3(projectileSize, projectileSize, projectileSize);

            // Instantiate the projectile at the position and rotation of this transform
            Rigidbody clone;
            clone = Instantiate(rb, transform.position, transform.rotation);

            // Give the cloned object an initial velocity along the current
            // object's Z axis
            clone.velocity = transform.TransformDirection(Vector3.forward * projectileSpeed);
        }
    }
}

然后我尝试从屏幕中间向鼠标位置投射一条射线,然后将我的武器旋转到射线与我的世界碰撞的点。但是当我 运行 它向四面八方射击时 :=o (没有错误)需要一些帮助来解决这个问题 :) 这是我的武器瞄准脚本:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class weapon_aiming : MonoBehaviour
{
    public Camera camera;
    private bool ray_hit_something = false;

    void Update()
    {
        RaycastHit hit;
        Ray ray = camera.ScreenPointToRay(Input.mousePosition);

        if (Physics.Raycast(ray, out hit))
        {
            ray_hit_something = true;
        } else
        {
            ray_hit_something = false;
        }

        if (ray_hit_something == true) { 
            transform.LookAt(Camera.main.ViewportToScreenPoint(hit.point));
        }
    }
}

只需使用 LookAt(hit.point),因为 LookAt 期望在世界 space 中有一个位置,而 hit.point 已经在世界 space:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class weapon_aiming : MonoBehaviour
{
    public Camera camera;
    private bool ray_hit_something = false;

    void Update()
    {
        RaycastHit hit;
        Ray ray = camera.ScreenPointToRay(Input.mousePosition);

        ray_hit_something = Physics.Raycast(ray, out hit);

        if (ray_hit_something) { 
            transform.LookAt(hit.point);
        }
    }
}