【发布时间】:2019-06-30 20:22:05
【问题描述】:
我是 Unity 新手,我正在为一个学校项目创建一个小型 2D 射击游戏,我已经设法在主角中拥有一个功能性射击系统,它甚至可以使用 Unity 物理从一些物体上反弹。
我现在想集成一条可以预测子弹轨迹的瞄准线,包括物体上的反弹(泡泡射击风格)。
我发现了一个使用 Raycast 和 Line Renderer 的脚本,据说它可以做到这一点,我尝试将它集成到我的枪脚本中,但虽然它没有给出任何错误,但在我测试游戏时它根本没有显示任何内容。我不知道问题出在我放入 Line Renderer 组件的设置中还是在脚本中。
有人可以帮助我了解我的错误在哪里并指出正确的方法吗?
我的目标是:
我的线渲染器组件定义:
我的武器脚本:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(LineRenderer))]
public class Weapon : MonoBehaviour
{
[Range(1, 5)]
[SerializeField] private int _maxIterations = 3;
[SerializeField] private float _maxDistance = 10f;
public int _count;
public LineRenderer _line;
public Transform Firepoint;
public GameObject BulletPrefab;
public GameObject FirePrefab;
void Start()
{
_line = GetComponent<LineRenderer>();
}
// Update is called once per frame
void Update()
{
if (Input.GetButtonDown("Fire1"))
{
Shoot();
}
_count = 0;
_line.SetVertexCount(1);
_line.SetPosition(0, transform.position);
_line.enabled = RayCast(new Ray(transform.position, transform.forward));
}
void Shoot()
{
//shooting logic
var destroyBullet = Instantiate(BulletPrefab, Firepoint.position, Firepoint.rotation);
Destroy(destroyBullet, 10f);
var destroyFire = Instantiate(FirePrefab, Firepoint.position, Firepoint.rotation);
Destroy(destroyFire, 0.3f);
}
private bool RayCast(Ray ray)
{
RaycastHit hit;
if (Physics.Raycast(ray, out hit, _maxDistance) && _count <= _maxIterations - 1)
{
_count++;
var reflectAngle = Vector3.Reflect(ray.direction, hit.normal);
_line.SetVertexCount(_count + 1);
_line.SetPosition(_count, hit.point);
RayCast(new Ray(hit.point, reflectAngle));
return true;
}
_line.SetVertexCount(_count + 2);
_line.SetPosition(_count + 1, ray.GetPoint(_maxDistance));
return false;
}
}
【问题讨论】:
标签: unity3d 2d game-physics 2d-games raycasting