Unity 3D如何将武器对准射线投射命中

问题描述 投票:0回答:2

我有一种射击弹丸的武器,我试图将其朝射线投射命中旋转。我还附加了两个脚本,一个用于射击,另一个用于瞄准射击脚本。这里是我的武器脚本,可以使我的弹丸生效:

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));
        }
    }
}
c# unity3d raycasting
2个回答
0
投票

我将其更改为LookAt(hit.point),对ruzihm的效果很好


0
投票

只需使用LookAt(hit.point),因为LookAt期望在世界空间中定位并且hit.point已经在世界空间中:

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);
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.