c# - Unity 3D如何将武器瞄准光线投射
问题描述
我有一个发射弹丸的武器,我尝试将武器旋转到射线命中。我还附上了两个脚本,我的武器一个用于射击,一个用于瞄准射击脚本工作正常。这是我的武器脚本,它启动了我的射弹:
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
预期使用世界空间中的位置并且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);
}
}
}
推荐阅读
- assembly - 在 x86 sasm 程序集中读取文件的特定字节
- r - geom_ribbon 中 y-lim 上方的颜色区域
- scala - 只要我忽略返回值,将函数 [X, Y] X => Y 转换为 X => () 是否安全?
- typescript - 在打字稿中组合两个数组后如何获得唯一元素?
- firebase - 什么推送通知技术可以满足我的需求?
- python - 正则表达式匹配 m a 后跟 n b 且 m > n > 0
- python - 遍历列表字典 - python
- go - 在 Sarama 中重命名 kafka 消费者组?
- laravel - 如何根据 vue 中的类别选项卡的内容来拆分产品
- python - 用Python中由相邻单元组成的向量表示体素的有效方法?